pppp
Print Hello World
In this example, you will learn to print 'Hello World' in JavaScript in three different ways.
A "Hello, World!" is a simple program that prints Hello, World! on the screen.
Since it's a very simple program, this program is often used to introduce a new programming language to beginners.
We will use these three ways to print 'Hello, World!'
.
console.log()
alert()
document.write()
1. Using console.log()
console.log()
is used in debugging the code.
Source Code
// the hello world program
console.log('Hello World');
Output
Hello, World!
Here, the first line is a comment.
// the hello world program
The second line
console.log('Hello, World!');
prints the 'Hello, World!' string to the console.
2. Using alert()
The alert()
method displays an alert box over the current window with the specified message.
Source Code
// the hello world program
alert("Hello, World!");
3. Using document.write()
document.write()
is used when you want to print the content to the HTML document.
Source Code
// the hello world program
document.write('Hello, World!');
Add Two Numbers
In this example, you will learn how to add two numbers and display their sum using various methods in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Variables and Constants
JavaScript Operators
We use the +
operator to add two or more numbers.
Example 1: Add Two Numbers
const num1 = 5;
const num2 = 3;
// add two numbers
const sum = num1 + num2;
// display the sum
console.log('The sum of ' + num1 + ' and ' + num2 + ' is: ' + sum);
Output
The sum of 5 and 3 is: 8
Example 2: Add Two Numbers Entered by the User
// store input numbers
const num1 = parseInt(prompt('Enter the first number '));
const num2 = parseInt(prompt('Enter the second number '));
//add two numbers
const sum = num1 + num2;
// display the sum
console.log(`The sum of ${num1} and ${num2} is ${sum}`);
Output
Enter the first number 5
Enter the second number 3
The sum of 5 and 3 is: 8
The above program asks the user to enter two numbers.
Here, prompt()
is used to take inputs from the user.
parseInt()
is used to convert the user input string to number.
const num1 = parseInt(prompt('Enter the first number '));
const num2 = parseInt(prompt('Enter the second number '));
Then, the sum of the numbers is computed.
const sum = num1 + num2;
Finally, the sum is displayed.
To display the result, we have used the template literal ` `
.
This allows us to include variables inside strings.
console.log(`The sum of ${num1} and ${num2} is ${sum}`);
To include variables inside ``
, you need to use the ${variable}
format.
Note: Template literals was introduced in ES6 and some browsers may not support them.
To learn more, visit, JavaScript template literals support.
Find the Square Root
In this example, you'll learn to write a program to find the square root of a number in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Variables and Constants
JavaScript Math sqrt()
To find the square root of a number in JavaScript, you can use the built-in Math.sqrt()
method.
Its syntax is:
Math.sqrt(number);
Here, the Math.sqrt()
method takes a number and returns its square root.
Example: Square Root of a Number
// take the input from the user
const number = prompt('Enter the number: ');
const result = Math.sqrt(number);
console.log(`The square root of ${number} is ${result}`);
Output
Enter the number: 9
The square root of 9 is 3
Example 2: Square Root of Different Data Types
const number1 = 2.25;
const number2 = -4;
const number3 = 'hello';
const result1 = Math.sqrt(number1);
const result2 = Math.sqrt(number2);
const result3 = Math.sqrt(number3);
console.log(`The square root of ${number1} is ${result1}`);
console.log(`The square root of ${number2} is ${result2}`);
console.log(`The square root of ${number3} is ${result3}`);
Output
The square root of 2.25 is 1.5
The square root of -4 is NaN
The square root of hello is NaN
If 0 or a positive number is passed in the Math.sqrt()
method, then the square root of that number is returned.
If a negative number is passed, NaN
is returned.
If a string is passed, NaN
is returned.
Calculate the Area of a Triangle
In this example, you'll learn to write a program to calculate the area of a triangle in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Operators
JavaScript Math sqrt()
If you know the base and height of a triangle, you can find the area using the formula:
area = (base * height) / 2
Example 1: Area When Base and Height is Known
const baseValue = prompt('Enter the base of a triangle: ');
const heightValue = prompt('Enter the height of a triangle: ');
// calculate the area
const areaValue = (baseValue * heightValue) / 2;
console.log(
`The area of the triangle is ${areaValue}`
);
Output
Enter the base of a triangle: 4
Enter the height of a triangle: 6
The area of the triangle is 12
If you know all the sides of a triangle, you can find the area using Herons' formula.
If a
, b
and c
are the three sides of a triangle, then
s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))
Example 2: Area When All Sides are Known
// JavaScript program to find the area of a triangle
const side1 = parseInt(prompt('Enter side1: '));
const side2 = parseInt(prompt('Enter side2: '));
const side3 = parseInt(prompt('Enter side3: '));
// calculate the semi-perimeter
const s = (side1 + side2 + side3) / 2;
//calculate the area
const areaValue = Math.sqrt(
s * (s - side1) * (s - side2) * (s - side3)
);
console.log(
`The area of the triangle is ${areaValue}`
);
Output
Enter side1: 3
Enter side2: 4
Enter side3: 5
The area of the triangle is 6
Here, we have used the Math.sqrt()
method to find the square root of a number.
Note: If a triangle cannot be formed from the given sides, the program will not run correctly.
Swap Two Variables
In this example, you will learn to write a program to swap two variables in JavaScript using various methods.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Variables and Constants
JavaScript Operators
Example 1: Using a Temporary Variable
//JavaScript program to swap two variables
//take input from the users
let a = prompt('Enter the first variable: ');
let b = prompt('Enter the second variable: ');
//create a temporary variable
let temp;
//swap variables
temp = a;
a = b;
b = temp;
console.log(`The value of a after swapping: ${a}`);
console.log(`The value of b after swapping: ${b}`);
Output
Enter the first variable: 4
Enter the second variable: 2
The value of a after swapping: 2
The value of b after swapping: 4
Here,
We created a temp variable to store the value of a temporarily.
We assigned the value of b to a.
The value of temp is assigned to b
As a result, the value of the variables are swapped.
Note: You can also swap strings or other data types using this method.
Example 2: Using es6(ES2015) Destructuring assignment
//JavaScript program to swap two variables
//take input from the users
let a = prompt('Enter the first variable: ');
let b = prompt('Enter the second variable: ');
//using destructuring assignment
[a, b] = [b, a];
console.log(`The value of a after swapping: ${a}`);
console.log(`The value of b after swapping: ${b}`);
Output
Enter the first variable: 4
Enter the second variable: 2
The value of a after swapping: 2
The value of b after swapping: 4
Here, a new es6 feature, called destructuring assignment [a, b] = [b, a]
, is used to swap the value of two variables.
If [a, b] = [1, 2, 3]
, the value of a will be 1 and value of b will be 2.
First a temporary array [b, a] is created.
Here the value of [b, a] will be [2, 4]
.
The destructuring of the array is done, i.e [a, b] = [2, 4]
.
As a result, the value of the variables are swapped.
You can learn more about destructuring in JavaScript Destructing Assignment.
Note: You can also swap strings or other data types using this method.
You can also swap the variable's values using the arithmetic operators.
Example 3: Using Arithmetic Operators
//JavaScript program to swap two variables
//take input from the users
let a = parseInt(prompt('Enter the first variable: '));
let b = parseInt(prompt('Enter the second variable: '));
// addition and subtraction operator
a = a + b;
b = a - b;
a = a - b;
console.log(`The value of a after swapping: ${a}`);
console.log(`The value of b after swapping: ${b}`);
Output
Enter the first variable: 4
Enter the second variable: 2
The value of a after swapping: 2
The value of b after swapping: 4
This method only uses the two variables and swaps the value of the variables using arithmetic operators +
and -
.
Here, parseInt()
is used because prompt()
takes input from the user as a string.
And when numeric strings are added, it behaves as a string.
For example, '2' + '3' = '23'
.
So parseInt()
converts a numeric string to number.
To learn more about the type conversion, go to JavaScript Type Conversions.
Let's see how the above program swaps values.
Initially, a is 4 and b is 2.
a = a + b
assigns the value 4 + 2
to a (now 6).
b = a - b
assigns the value 6 - 2
to b (now 4).
a = a - b
assign the value 6 - 4
to a (now 2).
Finally, a is 2 and b is 4.
Note: You can use arithmetic operators (+
, -
) if both variables are of number type.
Example 4: Using Bitwise XOR operator
//JavaScript program to swap two variables
//take input from the users
let a = prompt('Enter the first variable: ');
let b = prompt('Enter the second variable: ');
// XOR operator
a = a ^ b
b = a ^ b
a = a ^ b
console.log(`The value of a after swapping: ${a}`);
console.log(`The value of b after swapping: ${b}`);
Output
Enter the first variable: 4
Enter the second variable: 2
The value of a after swapping: 2
The value of b after swapping: 4
Bitwise XOR operator evaluates to true
if both operands are different.
To learn more about bitwise operators, visit JavaScript Bitwise Operators.
Let's see how the above program swaps values.
Initially, a is 4 and b is 2.
a = a ^ b
assigns the value 4 ^ 2
to a (now 6).
b = a ^ b
assigns the value 6 ^ 2
to b (now 4).
a = a ^ b
assign the value 6 ^ 4
to a (now 2).
Finally, a is 2 and b is 4.
Note: You can use this method for only integer (whole number) values.
Solve Quadratic Equation
In this example, you will learn to write a program that solves a quadratic equation in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript if...else Statement
JavaScript Math sqrt()
This program computes roots of a quadratic equation when its coefficients are known.
The standard form of a quadratic equation is:
ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0
To find the roots of such equation, we use the formula,
(root1,root2) = (-b ± √b2-4ac)/2
The term b2-4ac
is known as the discriminant of a quadratic equation.
It tells the nature of the roots.
If the discriminant is greater than 0, the roots are real and different.
If the discriminant is equal to 0, the roots are real and equal.
If the discriminant is less than 0, the roots are complex and different.
Nature of the roots of quadratic equations
Example: Roots of a Quadratic Equation
// program to solve quadratic equation
let root1, root2;
// take input from the user
let a = prompt("Enter the first number: ");
let b = prompt("Enter the second number: ");
let c = prompt("Enter the third number: ");
// calculate discriminant
let discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
// result
console.log(`The roots of quadratic equation are ${root1} and ${root2}`);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
// result
console.log(`The roots of quadratic equation are ${root1} and ${root2}`);
}
// if roots are not real
else {
let realPart = (-b / (2 * a)).toFixed(2);
let imagPart = (Math.sqrt(-discriminant) / (2 * a)).toFixed(2);
// result
console.log(
`The roots of quadratic equation are ${realPart} + ${imagPart}i and ${realPart} - ${imagPart}i`
);
}
Output 1
Enter the first number: 1
Enter the second number: 6
Enter the third number: 5
The roots of quadratic equation are -1 and -5
The above input values satisfy the first if
condition.
Here, the discriminant will be greater than 0 and the corresponding code is executed.
Output 2
Enter the first number: 1
Enter the second number: -6
Enter the third number: 9
The roots of quadratic equation are 3 and 3
The above input values satisfy the else if
condition.
Here, the discriminant will be equal to 0 and the corresponding code is executed.
Output 3
Enter the first number: 1
Enter the second number: -3
Enter the third number: 10
The roots of quadratic equation are 1.50 + 2.78i and 1.50 - 2.78i
In the above output, the discriminant will be less than 0 and the corresponding code is executed.
In the above program, the Math.sqrt()
method is used to find the square root of a number.
You can see that toFixed(2)
is also used in the program.
This rounds up the decimal number to two decimal values.
The above program uses an if...else
statements.
If you want to learn more about if...else
statements, go to JavaScript if...else Statement.
Convert Kilometers to Miles
In this example, you will learn how to convert kilometer values to miles in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Variables and Constants
JavaScript Operators
We know that 1 kilometer is equal to 0.621371 miles.
So to convert kilometers to miles, you can use the formula:
miles = kilometers *
0.621371
Example 1: Kilometers to Miles
// taking kilometers input from the user
const kilometers = prompt("Enter value in kilometers: ")
// conversion factor
const factor = 0.621371
// calculate miles
const miles = kilometers * factor
console.log(`${kilometers} kilometers is equal to ${miles} miles.`);
Output
Enter value in kilometers: 2.2
2.2 kilometers is equal to 1.3670162000000001 miles.
Here, the kilometers variable is used to store the kilometer value from the user.
Then kilometer value is multiplied with factor to convert into miles.
To convert miles to kilometers, you can use formula:
kilometers = miles / factor
Convert Celsius to Fahrenheit
In this example, you will learn to convert Celsius value to Fahrenheit in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Variables and Constants
JavaScript Operators
You can convert the celsius value to fahrenheit by using the formula:
fahrenheit = celsius * 1.8 + 32
Example: Celsius to Fahrenheit
// program to convert celsius to fahrenheit
// ask the celsius value to the user
const celsius = prompt("Enter a celsius value: ");
// calculate fahrenheit
const fahrenheit = (celsius * 1.8) + 32
// display the result
console.log(`${celsius} degree celsius is equal to ${fahrenheit} degree fahrenheit.`);
Output
Enter a celsius value: 55
55 degree celsius is equal to 131 degree fahrenheit.
In the above program, the user enters the celsius value and is stored in the celsius variable.
Then the fahrenheit formula is used to convert celsius value to fahrenheit.
You can convert fahrenheit value to celsius using the formula:
celsius = (fahrenheit - 32) / 1.8
Generate a Random Number
In this example, you will learn to generate a random number in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Math random()
JavaScript Math floor()
In JavaScript, you can generate a random number with the Math.random()
function.
Math.random()
returns a random floating-point number ranging from 0 to less than 1 (inclusive of 0 and exclusive of 1)
Example 1: Generate a Random Number
// generating a random number
const a = Math.random();
console.log(a);
Output
0.5856407221615856
Here, we have declared a variable a and assigned it a random number greater than or equal to 0 and less than 1.
Note: You might get a different output in the above program as Math.random()
will generate a random number.
We can use this value in the range (0,1) to find the random value between any two numbers using formula:
Math.random() * (highestNumber - lowestNumber) + lowestNumber
Example 2: Get a Random Number between 1 and 10
// generating a random number
const a = Math.random() * (10-1) + 1
console.log(`Random value between 1 and 10 is ${a}`);
Output
Random value between 1 and 10 is 7.392579122270686
This will show a random floating-point number greater than 1 and less than 10.
All the above examples give floating-point random numbers.
You can use Math.floor()
to get a random integer value.
Math.floor()
returns the number by decreasing the value to the nearest integer value.
For example,
Math.floor(5.389); // 5
Math.floor(5.9); // 5
The syntax to find the random integer value between two numbers:
Math.floor(Math.random() * (highestNumber - lowestNumber)) + lowestNumber
Example 3: Integer Value between 1 and 10
// generating a random number
const a = Math.floor(Math.random() * (10 - 1)) + 1;
console.log(`Random value between 1 and 10 is ${a}`);
Output
Random value between 1 and 10 is 2
This will show integer output between 1 (inclusive) to 10 (exclusive), i.e.
(1 to 9).
Here, Math.floor()
is used to convert decimal to integer value.
Similarly, if you want to find the random integer in between min (inclusive) to max (inclusive), you can use the following formula:
Math.floor(Math.random() * (max - min + 1)) + min
Example 4: Integer Value between Two Numbers (Inclusive)
// input from the user
const min = parseInt(prompt("Enter a min value: "));
const max = parseInt(prompt("Enter a max value: "));
// generating a random number
const a = Math.floor(Math.random() * (max - min + 1)) + min;
// display a random number
console.log(`Random value between ${min} and ${max} is ${a}`);
Output
Enter a min value: 1
Enter a max value: 50
Random value between 1 and 50 is 47
This will show the integer output between min (inclusive) to max (inclusive).
Check if a number is Positive, Negative, or Zero
In this example, you will learn to check whether the number entered by the user is positive, negative or zero.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Comparison and Logical Operators
JavaScript if...else Statement
You will be using the if...else if...else
statement to write the program.
Example 1: Check Number Type with if...else if...else
// program that checks if the number is positive, negative or zero
// input from the user
const number = parseInt(prompt("Enter a number: "));
// check if number is greater than 0
if (number > 0) {
console.log("The number is positive");
}
// check if number is 0
else if (number == 0) {
console.log("The number is zero");
}
// if number is less than 0
else {
console.log("The number is negative");
}
Output
Enter a number: 0
The number is zero.
The above program checks if the number entered by the user is positive, negative or zero.
The condition number > 0
checks if the number is positive.
The condition number == 0
checks if the number is zero.
The condition number < 0
checks if the number is negative.
The above program can also be written using the nested if...else
statement.
Example 2: Check Number Type with nested if...else
// check if the number is positive, negative or zero
const number = prompt("Enter a number: ");
if (number >= 0) {
if (number == 0) {
console.log("The number is zero");
} else {
console.log("The number is positive");
}
} else {
console.log("The number is negative");
}
Output
Enter a number: 0
You entered number zero
The above program works the same as Example 1.
However, the second example uses the nested if...else
statement.
Check if a Number is Odd or Even
In this example, you will learn to write a JavaScript program to check if the number is odd or even.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Comparison and Logical Operators
JavaScript if...else Statement
JavaScript Ternary Operator
Even numbers are those numbers that are exactly divisible by 2.
The remainder operator %
gives the remainder when used with a number.
For example,
const number = 6;
const result = number % 4; // 2
Hence, when %
is used with 2, the number is even if the remainder is zero.
Otherwise, the number is odd.
Example 1: Using if...else
// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");
//check if the number is even
if(number % 2 == 0) {
console.log("The number is even.");
}
// if the number is odd
else {
console.log("The number is odd.");
}
Output
Enter a number: 27
The number is odd.
In the above program, number % 2 == 0
checks whether the number is even.
If the remainder is 0, the number is even.
In this case, 27 % 2 equals to 1.
Hence, the number is odd.
The above program can also be written using a ternary operator.
Example 2: Using Ternary Operator
// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");
// ternary operator
const result = (number % 2 == 0) ? "even" : "odd";
// display the result
console.log(`The number is ${result}.`);
Output
Enter a number: 5
The number is odd.
Find the Largest Among Three Numbers
In this example, you will learn to find the largest among three numbers in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Comparison and Logical Operators
JavaScript if...else Statement
You can find the largest among three numbers using the if...else
statement.
Example 1: Largest Number Among Three Numbers
// program to find the largest among three numbers
// take input from the user
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));
let largest;
// check the condition
if(num1 >= num2 && num1 >= num3) {
largest = num1;
}
else if (num2 >= num1 && num2 >= num3) {
largest = num2;
}
else {
largest = num3;
}
// display the result
console.log("The largest number is " + largest);
Output
Enter first number: -7
Enter second number: -5
Enter third number: -1
The largest number is -1
In the above program, parseFloat()
is used to convert numeric string to number.
If the string is a floating number, parseFloat()
converts the string into floating point number.
The numbers are compared with one another using greater than or equal to >=
operator.
And the if...else if...else
statement is used to check the condition.
Here, logical AND &&
is also used to check two conditions.
You can also use the JavaScript built-in Math.max()
function to find the largest among the numbers.
Example2: Using Math.max()
// program to find the largest among three numbers
// take input from the user
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));
const largest = Math.max(num1, num2, num3);
// display the result
console.log("The largest number is " + largest);
Output
Enter first number: 5
Enter second number: 5.5
Enter third number: 5.6
The largest number is 5.6
Math.max()
returns the largest number among the provided numbers.
You can use Math.min()
function to find the smallest among the numbers.
Check Prime Number
In this example, you will learn to write a JavaScript program to check if a number is a prime number or not.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript for loop
JavaScript if...else Statement
JavaScript break Statement
A prime number is a positive integer that is only divisible by 1 and itself.
For example, 2, 3, 5, 7, 11 are the first few prime numbers.
Example: Check Prime Number
// program to check if a number is prime or not
// take input from the user
const number = parseInt(prompt("Enter a positive number: "));
let isPrime = true;
// check if number is equal to 1
if (number === 1) {
console.log("1 is neither prime nor composite number.");
}
// check if number is greater than 1
else if (number > 1) {
// looping through 2 to number-1
for (let i = 2; i < number; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
console.log(`${number} is a prime number`);
} else {
console.log(`${number} is a not prime number`);
}
}
// check if number is less than 1
else {
console.log("The number is not a prime number.");
}
Output
Enter a positive number: 23
23 is a prime number.
In the above program, the user is prompted to enter a number.
The number entered by the user is checked if it is greater than 1 using if...else if...
else
statement.
1 is considered neither prime nor composite.
All negative numbers are excluded because prime numbers are positive.
Numbers greater than 1 are tested using a for
loop.
The for
loop is used to iterate through the positive numbers to check if the number entered by the user is divisible by positive numbers (2 to user-entered number minus 1).
The condition number % i == 0
checks if the number is divisible by numbers other than 1 and itself.
If the remainder value is evaluated to 0, that number is not a prime number.
The isPrime variable is used to store a boolean value: either true or false.
The isPrime variable is set to false if the number is not a prime number.
The isPrime variable remains true if the number is a prime number.
Print All Prime Numbers in an Interval
In this example, you will learn to write a JavaScript program to print all the prime numbers between two numbers entered by a user.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript if...else Statement
JavaScript for loop
JavaScript break Statement
A prime number is a positive integer that is only divisible by 1 and itself.
For example, 2, 3, 5, 7, 11 are the first few prime numbers.
For example, 4 is not a prime number because it is divisible by 1, 2 and 4 itself.
It is a composite number.
Example: Print Prime Numbers
// program to print prime numbers between the two numbers
// take input from the user
const lowerNumber = parseInt(prompt('Enter lower number: '));
const higherNumber = parseInt(prompt('Enter higher number: '));
console.log(`The prime numbers between ${lowerNumber} and ${higherNumber} are:`);
// looping from lowerNumber to higherNumber
for (let i = lowerNumber; i <= higherNumber; i++) {
let flag = 0;
// looping through 2 to user input number
for (let j = 2; j < i; j++) {
if (i % j == 0) {
flag = 1;
break;
}
}
// if number greater than 1 and not divisible by other numbers
if (i > 1 && flag == 0) {
console.log(i);
}
}
Output
Enter lower number: 2
Enter higher number : 10
The prime numbers between 2 and 10 are:
2
3
5
7
In the above program, the user is prompted to enter lower and higher bound numbers.
Then the prime number between those numbers (including the lower and higher bounds, if any) are listed out.
Two nested for
loops are used in the above program.
The first for
loop is used to loop between the numbers provided by the user.
In this case, from 2 to 10.
A variable flag is set to 0.
The second for
loop is used to loop between 2 to the number that is stored in i.
Inside the second loop, the value of i is divided by each number from 2 to value one less than i (i - 1).
While dividing, if any number remainder results in 0, that number is not a prime number.
So the variable flag is set to 1.
Finally, all the numbers that have a flag 0 (not divisible by other numbers) are printed.
Find the Factorial of a Number
In this example, you will learn to write a JavaScript program to calculate the factorial of a number.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript if...else Statement
JavaScript for loop
The factorial of a number is the product of all the numbers from 1 to that number.
For example,
factorial of 5 is equal to 1 * 2 * 3 * 4 * 5 = 120.
The factorial of a positive number n is given by:
factorial of n (n!) = 1 * 2 * 3 * 4.....n
The factorial of negative numbers do not exist and the factorial of 0 is 1.
Example: Find Factorial
// program to find the factorial of a number
// take input from the user
const number = parseInt(prompt('Enter a positive integer: '));
// checking if number is negative
if (number < 0) {
console.log('Error! Factorial for negative number does not exist.');
}
// if number is 0
else if (number === 0) {
console.log(`The factorial of ${number} is 1.`);
}
// if number is positive
else {
let fact = 1;
for (i = 1; i <= number; i++) {
fact *= i;
}
console.log(`The factorial of ${number} is ${fact}.`);
}
Output
Enter a positive integer: 5
The factorial of 5 is 120.
In the above program, the user is prompted to enter an integer.
Then if...else if...else
statement is used to check the condition of a number.
When the user enters a negative number, an error message is shown.
When the user enters 0, the factorial is 1.
When the user enters a positive integer, a for
loop is used to iterate over 1 to the number entered by the user to find the factorial.
Each number is multiplied and stored in the fact
variable.
Display the Multiplication Table
In this example, you will learn to generate the multiplication table of a number in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript for loop
Example 1: Multiplication Table Up to 10
// program to generate a multiplication table
// take input from the user
const number = parseInt(prompt('Enter an integer: '));
//creating a multiplication table
for(let i = 1; i <= 10; i++) {
// multiply i with number
const result = i * number;
// display the result
console.log(`${number} * ${i} = ${result}`);
}
Output
Enter an integer: 3
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
In the above program, the user is prompted to enter an integer value.
Then, the for
loop is used to iterate through 1 to 10 to create a multiplication table.
Example 2: Multiplication Table Up to a Range
/* program to generate a multiplication table
upto a range */
// take number input from the user
const number = parseInt(prompt('Enter an integer: '));
// take range input from the user
const range = parseInt(prompt('Enter a range: '));
//creating a multiplication table
for(let i = 1; i <= range; i++) {
const result = i * number;
console.log(`${number} * ${i} = ${result}`);
}
Output
Enter an integer: 7
Enter a range: 5
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
In the above example, the user is prompted to enter an integer and also a range for which they want to create a multiplication table.
The user enters an integer (here 7) and a range (here 5).
Then a multiplication table is created using a for
loop for that range.
Print the Fibonacci Sequence
In this example, you will learn to program a Fibonacci sequence in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript for loop
JavaScript while and do...while Loop
A fibonacci sequence is written as:
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1.
After that, the next term is defined as the sum of the previous two terms.
Example 1: Fibonacci Series Up to n Terms
// program to generate fibonacci series up to n terms
// take input from the user
const number = parseInt(prompt('Enter the number of terms: '));
let n1 = 0, n2 = 1, nextTerm;
console.log('Fibonacci Series:');
for (let i = 1; i <= number; i++) {
console.log(n1);
nextTerm = n1 + n2;
n1 = n2;
n2 = nextTerm;
}
Output
Enter the number of terms: 4
Fibonacci Series:
0
1
1
2
In the above program, the user is prompted to enter the numbers of terms that they want in the Fibonacci series.
The for
loop iterates up to the number entered by the user.
0 is printed at first.
Then, in each iteration, the value of the second term is stored in variable n1 and the sum of two previous terms is stored in variable n2.
Example 2: Fibonacci Sequence Up to a Certain Number
// program to generate fibonacci series up to a certain number
// take input from the user
const number = parseInt(prompt('Enter a positive number: '));
let n1 = 0, n2 = 1, nextTerm;
console.log('Fibonacci Series:');
console.log(n1); // print 0
console.log(n2); // print 1
nextTerm = n1 + n2;
while (nextTerm <= number) {
// print the next term
console.log(nextTerm);
n1 = n2;
n2 = nextTerm;
nextTerm = n1 + n2;
}
Output
Enter a positive number: 5
Fibonacci Series:
0
1
1
2
3
5
In the above example, the user is prompted to enter a number up to which they want to print the Fibonacci series.
The first two terms 0 and 1 are displayed beforehand.
Then, a while
loop is used to iterate over the terms to find the Fibonacci series up to the number entered by the user.
Check Armstrong Number
In this example, you will learn to write a program in JavaScript to check whether a number is an Armstrong number or not.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Operators
JavaScript while and do...while Loop
A positive integer is called an Armstrong number (of order n) if
abcd...
= an + bn + cn + dn + ...
In the case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself.
For example, 153 is an Armstrong number because
153 = 1*1*1 + 5*5*5 + 3*3*3
Similarly, 1634 is an Armstrong number because:
1634 = 1*1*1*1 + 6*6*6*6* + 3*3*3*3 + 4*4*4*4
Example 1: Check Armstrong Number of Three Digits
// program to check an Armstrong number of three digits
let sum = 0;
const number = prompt('Enter a three-digit positive integer: ');
// create a temporary variable
let temp = number;
while (temp > 0) {
// finding the one's digit
let remainder = temp % 10;
sum += remainder * remainder * remainder;
// removing last digit from the number
temp = parseInt(temp / 10); // convert float into integer
}
// check the condition
if (sum == number) {
console.log(`${number} is an Armstrong number`);
}
else {
console.log(`${number} is not an Armstrong number.`);
}
Output
Enter a three-digit positive integer: 153
153 is an Armstrong number.
The above program takes an input from the user.
Then,
The number entered by the user is stored in a temporary variable temp
.
A while
loop is used to iterate a three-digit value.
The modulus operator %
is used to obtain each digit number.
When a number is divided by 10, the remainder is the last digit.
In the first iteration, 153 % 10
gives 3.
The remainder digit's cube is calculated by multiplying the digit three times.
And the cube is added to the sum
variable.
The digit is divided by 10 to remove the last digit.
The while
loop continues iterating and dividing the number by 10 until the number is 0.
Finally, the sum is compared with the number entered by the user.
If the sum and the number are equal, the number is an Armstrong number.
Note: In the above program, the cube of a number could be calculated using an exponent operator **
.
For example, sum += remainder ** 3;
Example 2: Check Armstrong Number of n Digits
// program to check an Armstrong number of n digits
// take an input
const number = prompt("Enter a positive integer");
const numberOfDigits = number.length;
let sum = 0;
// create a temporary variable
let temp = number;
while (temp > 0) {
let remainder = temp % 10;
sum += remainder ** numberOfDigits;
// removing last digit from the number
temp = parseInt(temp / 10); // convert float into integer
}
if (sum == number) {
console.log(`${number} is an Armstrong number`);
}
else {
console.log(`${number} is not an Armstrong number.`);
}
Output
Enter a positive integer: 92727
92727 is an Armstrong number
In the above program, an Armstrong number of n digits is checked.
When the user enters a number, it is taken as a string.
The length
property returns the length of a string.
The number entered by the user is stored in a temp
variable.
And a while
loop is used to iterate until its value is less than 0.
Each digit of the number is raised to the power of the length of the number.
Find Armstrong Number in an Interval
In this example, you will learn to write a program in JavaScript to find an Armstrong number between two integer values.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript for loop
A positive integer is called an Armstrong number (of order n) if:
abcd...
= an + bn + cn + dn + ...
In the case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself.
For example, 153 is an Armstrong number because:
153 = 1*1*1 + 5*5*5 + 3*3*3
Similarly, 1634 is an Armstrong number because:
1634 = 1*1*1*1 + 6*6*6*6* + 3*3*3*3 + 4*4*4*4
Before trying this program, visit JavaScript Program to Check Armstrong Number.
Example: Armstrong Numbers Between Two Intervals
// program to find Armstrong number between intervals
// take an input
const lowNumber = parseInt(prompt('Enter a positive low integer value: '));
const highNumber = parseInt(prompt('Enter a positive high integer value: '));
console.log ('Armstrong Numbers:');
// looping through lowNumber to highNumber
for (let i = lowNumber; i <= highNumber; i++) {
// converting number to string
let numberOfDigits = i.toString().length;
let sum = 0;
// create a temporary variable
let temp = i;
/* loop through a number to find if
a number is an Armstrong number */
while (temp > 0) {
let remainder = temp % 10;
sum += remainder ** numberOfDigits;
// removing last digit from the number
temp = parseInt(temp / 10); // convert float into integer
}
if (sum == i) {
console.log(i);
}
}
Output
Enter a positive low integer value: 8
Enter a positive high integer value: 500
Armstrong Numbers:
8
9
153
370
371
407
In the above program, the user is prompted to enter two integers.
One is the lower interval integer and another is the higher integer value.
The parseInt()
converts the numeric string value to an integer value.
The for
loop is used to loop through the two numbers provided by the user.
The toString()
method is used to convert the number to a string.
And the length
property is used to find the length of a string.
Hence, in this case, length
gives the total digits in the number.
let numberOfDigits = i.toString().length;
In the first for
loop iteration (i = 8),
The lower number entered by the user is stored in a temporary variable temp
.
A while
loop is used to iterate the number.
The modulus operator %
is used to obtain each digit number.
When a number is divided by 10, the remainder is the last digit.
In the first iteration, 8 % 10
gives 8.
The remainder is multiplied by the number of digits in that number (here 1) and the sum is calculated.
The digit is divided by 10 to remove the last digit, i.e.
8 / 10
gives 0.
Finally, the sum is compared with the number entered by the user.
If the sum and the number are equal, the Armstrong number is displayed.
The loop continues for all the numbers that are in between the lower and upper bounds provided by the user.
In the above example, the loop is executed from 8 to 500.
Make a Simple Calculator
In this example, you will learn to write a program to make a simple calculator in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript if...else Statement
JavaScript Switch Statement
Example 1: Simple Calculator with if..else if...else
// program for a simple calculator
// take the operator input
const operator = prompt('Enter operator ( either +, -, * or / ): ');
// take the operand input
const number1 = parseFloat(prompt('Enter first number: '));
const number2 = parseFloat(prompt('Enter second number: '));
let result;
// using if...else if...
else
if (operator == '+') {
result = number1 + number2;
}
else if (operator == '-') {
result = number1 - number2;
}
else if (operator == '*') {
result = number1 * number2;
}
else {
result = number1 / number2;
}
// display the result
console.log(`${number1} ${operator} ${number2} = ${result}`);
Output
Enter operator ( either +, -, * or / ): *
Enter first number: 3.4
Enter second number: 5.6
3.4 * 5.6 = 19.04
In the above example, the user is prompted to enter an operator (either +, -, * or /) and two numbers.
The parseFloat()
converts the numeric string value to a floating-point value.
The if...else if...if
statement is used to check the condition that the user has entered for the operator.
The corresponding operation is performed and the output is displayed.
Example 2: Simple Calculator with switch
// program for a simple calculator
let result;
// take the operator input
const operator = prompt('Enter operator ( either +, -, * or / ): ');
// take the operand input
const number1 = parseFloat(prompt('Enter first number: '));
const number2 = parseFloat(prompt('Enter second number: '));
switch(operator) {
case '+':
result = number1 + number2;
console.log(`${number1} + ${number2} = ${result}`);
break;
case '-':
result = number1 - number2;
console.log(`${number1} - ${number2} = ${result}`);
break;
case '*':
result = number1 * number2;
console.log(`${number1} * ${number2} = ${result}`);
break;
case '/':
result = number1 / number2;
console.log(`${number1} / ${number2} = ${result}`);
break;
default:
console.log('Invalid operator');
break;
}
Output
Enter operator: +
Enter first number: 4
Enter second number: 5
4 + 5 = 9
In above program, the user is asked to enter either +, -, * or /, and two numbers.
Then, the switch
statement executes cases based on the user input.
Find the Sum of Natural Numbers
In this example, you will learn to write a program that finds the sum of natural numbers in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript for loop
JavaScript while and do...while Loop
The positive integers 1, 2, 3, ...
are known as natural numbers.
Example 1: Sum of Natural Numbers Using for Loop
// program to display the sum of natural numbers
// take input from the user
const number = parseInt(prompt('Enter a positive integer: '));
let sum = 0;
// looping from i = 1 to number
// in each iteration, i is increased by 1
for (let i = 1; i <= number; i++) {
sum += i;
}
console.log('The sum of natural numbers:', sum);
Output
Enter a positive integer: 100
The sum of natural numbers: 5050
In the above program, the user is prompted to enter a number.
The parseInt()
converts the numeric string value to an integer value.
The for
loop is used to find the sum of natural numbers up to the number provided by the user.
The value of sum is 0 initially.
Then, a for
loop is used to iterate from i = 1 to 100
.
In each iteration, i is added to sum and the value of i
is increased by 1.
When i becomes 101, the test condition is false
and sum will be equal to 0 + 1 + 2 + ...
+ 100.
Example 2: Sum of Natural Numbers Using while Loop
// program to display the sum of natural numbers
// take input from the user
const number = parseInt(prompt('Enter a positive integer: '));
let sum = 0, i = 1;
// looping from i = 1 to number
while(i <= number) {
sum += i;
i++;
}
console.log('The sum of natural numbers:', sum);
Output
Enter a positive integer: 100
The sum of natural numbers: 5050
In the above program, the user is prompted to enter a number.
The while
loop is used to find the sum of natural numbers.
The while
loop continues until the number is less than or equal to 100.
During each iteration, i is added to the sum
variable and the value of i is increased by 1.
When i becomes 101, the test condition is false
and sum will be equal to 0 + 1 + 2 + ...
+ 100.
Check if the Numbers Have Same Last Digit
In this example, you will learn to write a program that checks whether the last digit of three numbers is the same or not in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Comparison and Logical Operators
JavaScript if...else Statement
Example: Check the Last Digit
/* program to check whether the last digit of three
numbers is same */
// take input
const a = prompt('Enter a first integer: ');
const b = prompt('Enter a second integer: ');
const c = prompt('Enter a third integer: ');
// find the last digit
const result1 = a % 10;
const result2 = b % 10;
const result3 = c % 10;
// compare the last digits
if(result1 == result2 && result1 == result3) {
console.log(`${a}, ${b} and ${c} have the same last digit.`);
}
else {
console.log(`${a}, ${b} and ${c} have different last digit.`);
}
Output
Enter a first integer: 8
Enter a second integer: 38
Enter a third integer: 88
8, 38 and 88 have the same last digit.
In the above example, the user is asked to enter three integers.
The three integer values are stored in variables a, b and c.
The last digit of an integer value is calculated using a modulus operator %
.
%
gives the remainder value.
For example, 58 % 10 gives 8.
All the last digits are then compared using if..else
statement and logical AND operator &&
operator.
Find HCF or GCD
In this example, you will learn to write a program that finds HCF or GCD in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript for loop
JavaScript if...else Statement
JavaScript while and do...while Loop
The Highest Common Factor (HCF) or Greatest Common Divisor (GCD) of two integers is the largest integer that can exactly divide both integers (without a remainder).
For example, the HCF of 60 and 72 is 12.
Example 1: Find HCF using for Loop
// program to find the HCF or GCD of two integers
let hcf;
// take input
const number1 = prompt('Enter a first positive integer: ');
const number2 = prompt('Enter a second positive integer: ');
// looping from 1 to number1 and number2
for (let i = 1; i <= number1 && i <= number2; i++) {
// check if is factor of both integers
if( number1 % i == 0 && number2 % i == 0) {
hcf = i;
}
}
// display the hcf
console.log(`HCF of ${number1} and ${number2} is ${hcf}.`);
Output
Enter a first integer: 60
Enter a second integer: 72
HCF of 60 and 72 is 12.
In the above program, the user is prompted to enter two positive numbers.
The for
loop is used to iterate from 1 to numbers entered by the user.
The if
condition and modulus operator %
is used to find the HCF of both numbers.
In the above condition, if both the integers number1 and number2 are exactly divisible by i, the highest integer value that fulfils that condition is calculated.
Example 2: HCF using while Loop and if...else
// program to find the HCF or GCD of two integers
// take input
let number1 = prompt('Enter a first positive integer: ');
let number2 = prompt('Enter a second positive integer: ');
// looping until both numbers are equal
while(number1 != number2){
if(number1 > number2) {
number1 -= number2;
}
else {
number2 -= number1;
}
}
// display the hcf
console.log(`HCF is ${number1}`);
Output
Enter a first integer: 60
Enter a second integer: 72
HCF is 12
In the above program, a while
loop is used with an if...else
statement.
In each iteration, the smaller integer is subtracted from the larger integer.
And the result is assigned to a variable holding the larger integer.
The while
loop continues until both the integers become equal.
Find LCM
In this example, you will learn to write a JavaScript program that finds the LCM of two numbers.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript if...else Statement
JavaScript while and do...while Loop
JavaScript for loop
The Least Common Multiple (LCM) of two integers is the smallest positive integer that is perfectly divisible by both integers.
For example, the LCM of 6 and 8 is 24.
Example 1: LCM Using while Loop and if Statement
// program to find the LCM of two integers
// take input
const num1 = prompt('Enter a first positive integer: ');
const num2 = prompt('Enter a second positive integer: ');
// higher number among number1 and number2 is stored in min
let min = (num1 > num2) ? num1 : num2;
// while loop
while (true) {
if (min % num1 == 0 && min % num2 == 0) {
console.log(`The LCM of ${num1} and ${num2} is ${min}`);
break;
}
min++;
}
Output
Enter a first positive integer: 6
Enter a second positive integer: 8
The LCM of 6 and 8 is 24
In the above program, the user is prompted to enter two positive integers.
The greater number among the numbers provided by the user is stored in a min variable.
The LCM of two numbers cannot be less than the greater number.
The while loop is used with an if
statement.
In each iteration,
The variable min
is divided by both the num1 and num2.
If both numbers' remainders are equal to 0, then it is the LCM and the break
statement terminates the program.
If both numbers' remainders are not equal to 0, the value of min is increased by 1 and the loop continues.
The while
loop continues until the condition is met.
if (min % num1 == 0 && min % num2 == 0)
The LCM of two numbers can also be found using the formula:
LCM = (num1*num2) / HCF
To learn about how to find the HCF, visit the JavaScript program to find HCF.
Example 2: LCM Calculation Using HCF
// program to find the LCM of two integers
let hcf;
// take input
const number1 = prompt('Enter a first positive integer: ');
const number2 = prompt('Enter a second positive integer: ');
// looping from 1 to number1 and number2 to find HCF
for (let i = 1; i <= number1 && i <= number2; i++) {
// check if is factor of both integers
if( number1 % i == 0 && number2 % i == 0) {
hcf = i;
}
}
// find LCM
let lcm = (number1 * number2) / hcf;
// display the hcf
console.log(`HCF of ${number1} and ${number2} is ${lcm}.`);
Output
Enter a first positive integer: 6
Enter a second positive integer: 8
The LCM of 6 and 8 is 24.
In the above program, firstly HCF of the numbers is calculated.
Then LCM is calculated using the given formula.
Find the Factors of a Number
In this example, you will learn to write a JavaScript program that finds all the factors of an integer.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript for loop
JavaScript if...else Statement
To be the factors of a number, the factor number should exactly divide the number (with 0 remainder).
For example,
The factor of 12 is 1, 2, 3, 4, 6, and 12.
Example: Factors of Positive Number
// program to find the factors of an integer
// take input
const num = prompt('Enter a positive number: ');
console.log(`The factors of ${num} is:`);
// looping through 1 to num
for(let i = 1; i <= num; i++) {
// check if number is a factor
if(num % i == 0) {
console.log(i);
}
}
Output
Enter a positive number: 12
The factors of 12 is:
1
2
3
4
6
12
In the above program, the user is prompted to enter a positive integer.
The for
loop is used to loop through 1 to the number entered by the user.
The modulus operator %
is used to check if num is exactly divisible.
In each iteration, a condition is checked if num is exactly divisible by i.
if(num % i == 0)
If the above condition is met, the number is displayed.
Find Sum of Natural Numbers Using Recursion
In this example, you will learn to write a JavaScript program that finds the sum of natural numbers using recursion.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Function and Function Expressions
JavaScript Recursion
The positive integers 1, 2, 3, ...
are known as natural numbers.
Example: Sum of Natural Numbers Using Recursion
// program to find the sum of natural numbers using recursion
function sum(num) {
if(num > 0) {
return num + sum(num - 1);
}
else {
return num;
}
}
// take input from the user
const number = parseInt(prompt('Enter a positive integer: '));
const result = sum(number);
// display the result
console.log(`The sum is ${result}`);
Output
Enter a positive integer: 5
The sum is 15
In the above program, the user is prompted to enter a number.
Then the sum()
function is called by passing the parameter (here 5) that the user entered.
If the number is greater than 0, the function calls itself by decreasing the number by 1.
This process continues until the number is 1.
When the number reaches 0, the program stops.
If the user enters a negative number, the negative number is returned and the program stops.
Here,
sum(5) returns 5 + sum(4)
sum(4) returns 5 + 4 + sum(3)
sum(3) returns 5 + 4 + 3 + sum(2)
sum(2) returns 5 + 4 + 3 + 2 + sum(1)
sum(1) returns 5 + 4 + 3 + 2 + 1 + sum(0)
sum(0) returns 5 + 4 + 3 + 2 + 1 + 0
Guess a Random Number
In this example, you will learn to write a JavaScript program where the user has to guess a number generated by a program.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Function and Function Expressions
JavaScript Math random()
JavaScript while and do...while Loop
Example: Program to Guess a Number
// program where the user has to guess a number generated by a program
function guessNumber() {
// generating a random integer from 1 to 10
const random = Math.floor(Math.random() * 10) + 1;
// take input from the user
let number = parseInt(prompt('Guess a number from 1 to 10: '));
// take the input until the guess is correct
while(number !== random) {
number = parseInt(prompt('Guess a number from 1 to 10: '));
}
// check if the guess is correct
if(number == random) {
console.log('You guessed the correct number.');
}
}
// call the function
guessNumber();
Output
Guess a number from 1 to 10: 1
Guess a number from 1 to 10: 8
Guess a number from 1 to 10: 5
Guess a number from 1 to 10: 4
You guessed the correct number.
Note: You will get different output values each time you run the program because each time a different number is generated.
In the above program, the guessNumber()
function is created where a random number from 1 to 10 is generated using Math.random()
function.
To learn more about how to generate a random number, visit JavaScript Generate Random Number.
The user is prompted to guess a number from 1 to 10.
The parseInt()
converts the numeric string value to an integer value.
The while
loop is used to take input from the user until the user guesses the correct answer.
The if...else
statement is used to check the condition.
The equal to ==
operator is used to check if the guess was correct.
if(number == random)
To learn more about the comparison operators, visit JavaScript Comparison Operator.
Shuffle Deck of Cards
In this example, you will learn to write a JavaScript program that shuffles a deck of cards.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array sort()
JavaScript for loop
Example: Shuffle Deck of Cards
// program to shuffle the deck of cards
// declare card elements
const suits = ["Spades", "Diamonds", "Club", "Heart"];
const values = [
"Ace",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"Jack",
"Queen",
"King",
];
// empty array to contain cards
let deck = [];
// create a deck of cards
for (let i = 0; i < suits.length; i++) {
for (let x = 0; x < values.length; x++) {
let card = { Value: values[x], Suit: suits[i] };
deck.push(card);
}
}
// shuffle the cards
for (let i = deck.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * i);
let temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
console.log('The first five cards are:');
// display 5 results
for (let i = 0; i < 5; i++) {
console.log(`${deck[i].Value} of ${deck[i].Suit}`)
}
Output
The first five cards are:
4 of Club
5 of Diamonds
Jack of Diamonds
2 of Club
4 of Spades
In the above program, the suits and values variables contain the elements of a card.
The nested for
loop is used to create a deck of cards.
We need to create a deck of cards containing each suits with all the values.
So the first for
loop iterates over all the suits and the second for
loop iterates over the values.
Then, the elements are created and added to the deck
array.
The array elements are stored as an object as:
[{Value: "Ace", Suit: "Spades"},{Value: "2", Suit: "Spades"}.....]
The second for
loop is used to shuffle the deck of cards.
Math.random()
generates a random number.
Math.floor()
returns the number by decreasing the value to the nearest integer value.
A random number is generated between 0 and 51 and two card positions are swapped.
The third for
loop is used to display the first five cards in the new deck.
Display Fibonacci Sequence Using Recursion
In this example, you will learn to program a Fibonacci sequence using recursion in JavaScript.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Recursion
A fibonacci sequence is written as:
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1.
After that, the next term is defined as the sum of the previous two terms.
Hence, the nth term is the sum of (n-1)th term and (n-2)th term.
Example: Fibonacci Sequence Upto nth Term using Recursion
// program to display fibonacci sequence using recursion
function fibonacci(num) {
if(num < 2) {
return num;
}
else {
return fibonacci(num-1) + fibonacci(num - 2);
}
}
// take nth term input from the user
const nTerms = prompt('Enter the number of terms: ');
if(nTerms <=0) {
console.log('Enter a positive integer.');
}
else {
for(let i = 0; i < nTerms; i++) {
console.log(fibonacci(i));
}
}
Output
Enter the number of terms: 5
0
1
1
2
3
In the above program, a recursive function fibonacci()
is used to find the fibonacci sequence.
The user is prompted to enter a number of terms up to which they want to print the Fibonacci sequence(here 5).
The if...else
statement is used to check if the number is greater than 0.
If the number is greater than 0, a for
loop is used to calculate each term recursively (calls the fibonacci()
function again).
Find Factorial of Number Using Recursion
In this example, you will learn to write a JavaScript program that finds the factorial of a number using recursion.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Recursion
JavaScript if...else Statement
The factorial of a number is the product of all the numbers from 1 to that number.
For example,
factorial of 5 is equal to 1 * 2 * 3 * 4 * 5 = 120.
The factorial of a positive number n is given by:
factorial of n (n!) = 1 * 2 * 3 * 4.....n
The factorial of negative numbers do not exist and the factorial of 0 is 1.
Example: Find Factorial Using Recursion
// program to find the factorial of a number
function factorial(x) {
// if number is 0
if (x == 0) {
return 1;
}
// if number is positive
else {
return x * factorial(x - 1);
}
}
// take input from the user
const num = prompt('Enter a positive number: ');
// calling factorial() if num is positive
if (num >= 0) {
const result = factorial(num);
console.log(`The factorial of ${num} is ${result}`);
}
else {
console.log('Enter a positive number.');
}
Output
Enter a positive number: 4
The factorial of 4 is 24
In the above program, the user is prompted to enter a number.
When the user enters a negative number, a message Enter a positive number. is shown.
When the user enters a positive number or 0, the function factorial(num)
gets called.
If the user enters the number 0, the program will return 1.
If the user enters a number greater than 0, the program will recursively call itself by decreasing the number.
This process continues until the number becomes 1.
Then when the number reaches 0, 1 is returned.
Here,
factorial(4) returns 4 * factorial(3)
factorial(3) returns 4 * 3 * factorial(2)
factorial(2) returns 4 * 3 * 2 * factorial(1)
factorial(1) returns 4 * 3 * 2 * 1 * factorial(0)
factorial(0) returns 4 * 3 * 2 * 1 * 1
Convert Decimal to Binary
In this example, you will learn to write a JavaScript program that converts a decimal number to a binary number.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Function and Function Expressions
JavaScript while and do...while Loop
Example 1: Convert Decimal to Binary
// program to convert decimal to binary
function convertToBinary(x) {
let bin = 0;
let rem, i = 1, step = 1;
while (x != 0) {
rem = x % 2;
console.log(
`Step ${step++}: ${x}/2, Remainder = ${rem}, Quotient = ${parseInt(x/2)}`
);
x = parseInt(x / 2);
bin = bin + rem * i;
i = i * 10;
}
console.log(`Binary: ${bin}`);
}
// take input
let number = prompt('Enter a decimal number: ');
convertToBinary(number);
Output
Step 1: 9/2, Remainder = 1, Quotient = 4
Step 2: 4/2, Remainder = 0, Quotient = 2
Step 3: 2/2, Remainder = 0, Quotient = 1
Step 4: 1/2, Remainder = 1, Quotient = 0
Binary: 1001
In the above program, the user is prompted to enter a decimal number.
The number entered by the user is passed as an argument to the convertToBinary()
function.
The while
loop is used until the number entered by the user becomes 0.
The binary value is calculated by:
bin = bin + rem * i;
Here, rem
is the modulus %
value of the number when divided by 2 and i gives the place value of the binary number.
Example 2: Convert Decimal to Binary Using toString()
// program to convert decimal to binary
// take input
const number = parseInt(prompt('Enter a decimal number: '));
// convert to binary
const result = number.toString(2);
console.log('Binary:' + ' ' + result);
Output
Enter a decimal number: 9
Binary: 1001
In the above program, the user is prompted to enter a number.
The parseInt()
method is used to convert a string value to an integer.
The JavaScript built-in method toString([radix])
returns a string value in a specified radix (base).
Here, toString(2)
converts the decimal number to binary number.
Find ASCII Value of Character
In this example, you will learn to write a JavaScript program that finds the ASCII value of a character.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String charCodeAt()
JavaScript String codePointAt()
ASCII stands for American Standard Code for Information Interchange.
ASCII is a numeric value that is given to different characters and symbols for computers to store and manipulate.
For example, the ASCII value of the letter 'A' is 65.
Resource: ASCII chart of all 127 characters in JavaScript.
Example 1: ASCII Value of Character Using charCodeAt()
// program to find the ASCII value of a character
// take input from the user
const string = prompt('Enter a character: ');
// convert into ASCII value
const result = string.charCodeAt(0);
console.log(`The ASCII value is: ${result}`);
Output
Enter a character: a
The ASCII value is: 97
In the above program, the charCodeAt()
method is used to find the ASCII value of a character.
The charCodeAt()
method takes in an index value and returns an integer representing its UTF-16 (16-bit Unicode Transformation Format) code.
If you don't pass the index value, the default index value will be 0.
If the index value is out of range, it gives NaN
.
Example 2: ASCII Value of Character Using codePointAt()
// program to find the ASCII value of a character
// take input from the user
const string = prompt('Enter a character: ');
// convert into ASCII value
const result = string.codePointAt(0);
console.log(`The ASCII value is: ${result}`);
Output
Enter a character: abc
The ASCII value is: 97
In the above program, the codePointAt()
method is used to find the ASCII value of a character.
The codePointAt()
method returns a Unicode code point value.
In the above program, the user inputs three-character string abc.
However, the index 0 is passed to the codePointAt()
method.
This gives the ASCII value of the first character (here a).
If you don't pass the index value, the default index value will be 0.
If the index value is out of range, it gives undefined
.
Check Whether a String is Palindrome or Not
In this example, you will learn to write a JavaScript program that checks if the string is palindrome or not.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript Function and Function Expressions
A string is a palindrome if it is read the same from forward or backward.
For example, dad reads the same either from forward or backward.
So the word dad is a palindrome.
Similarly, madam is also a palindrome.
Example 1: Check Palindrome Using for Loop
// program to check if the string is palindrome or not
function checkPalindrome(str) {
// find the length of a string
const len = string.length;
// loop through half of the string
for (let i = 0; i < len / 2; i++) {
// check if first and last string are same
if (string[i] !== string[len - 1 - i]) {
return 'It is not a palindrome';
}
}
return 'It is a palindrome';
}
// take input
const string = prompt('Enter a string: ');
// call the function
const value = checkPalindrome(string);
console.log(value);
Output
Enter a string: madam
It is a palindrome
In the above program, the checkPalindrome()
function takes input from the user.
The length of the string is calculated using the length
property.
The for
loop is used to iterate up to the half of the string.
The if
condition is used to check if the first and the corresponding last characters are the same.
This loop continues till the half of the string.
During the iteration, if any character of the string, when compared with its corresponding last string is not equal, the string is not considered a palindrome.
Example 2: Check Palindrome using built-in Functions
// program to check if the string is palindrome or not
function checkPalindrome(str) {
// convert string to an array
const arrayValues = string.split('');
// reverse the array values
const reverseArrayValues = arrayValues.reverse();
// convert array to string
const reverseString = reverseArrayValues.join('');
if(string == reverseString) {
console.log('It is a palindrome');
}
else {
console.log('It is not a palindrome');
}
}
//take input
const string = prompt('Enter a string: ');
checkPalindrome(string);
Output
Enter a string: hello
It is not a palindrome
In the above program, the palindrome is checked using the built-in methods available in JavaScript.
The split('')
method converts the string into individual array characters.
const arrayValues = string.split(''); // ["h", "e", "l", "l", "o"]
The reverse()
method reverses the position in an array.
// ["o", "l", "l", "e", "h"]
const reverseArrayValues = arrayValues.reverse();
The join('')
method joins all the elements of an array into a string.
const reverseString = reverseArrayValues.join(''); // "olleh"
Then the if...else
statement is used to check if the string and the reversed string are equal.
If they are equal, the string is a palindrome.
Note: The multiple lines of code can be reduced and written in one line:
const reverseString = string.split('').reverse().join('');
Sort Words in Alphabetical Order
In this example, you will learn to write a JavaScript program that sorts words in a string in alphabetical order.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript Arrays
JavaScript Array sort()
Example: Sort Words in Alphabetical Order
// program to sort words in alphabetical order
// take input
const string = prompt('Enter a sentence: ');
// converting to an array
const words = string.split(' ');
// sort the array elements
words.sort();
// display the sorted words
console.log('The sorted words are:');
for (const element of words) {
console.log(element);
}
Output
Enter a sentence: I am learning JavaScript
The sorted words are:
I
JavaScript
am
learning
In the above example, the user is prompted to enter a sentence.
The sentence is divided into array elements (individual words) using the split(' ')
method.
The split(' ')
method splits the string at whitespaces.
The elements of an array are sorted using the sort()
method.
The sort()
method sorts the strings in alphabetical and ascending order.
The for...of
loop is used to iterate over the array elements and display them.
Here, we are sorting alphabetically.
So, the expected output is am, I, JavaScript, and learning.
However, am is printed after I and JavaScript.
Why I and JavaScript are printed before am?
This is because I and J of JavaScript are in uppercase.
And, when we use the sort()
method, uppercase letters are placed before lowercase.
We can verify this by providing only lowercase input.
// program to sort words in alphabetical order
// take input
const string = prompt('Enter a sentence: ');
// converting to an array
const words = string.split(' ');
// sort the array elements
words.sort();
// display the sorted words
console.log('The sorted words are:');
for (const element of words) {
console.log(element);
}
Output
Enter a sentence: i am learning javascript
The sorted words are:
am
i
javascript
learning
Here, we get the expected output now.
Note: Instead of displaying from the array values, you can also convert the array elements back to the string and display the values as a string using join()
method.
words.join(' '); // I JavaScript am learning
Replace Characters of a String
In this example, you will learn to write a JavaScript program that replaces a character of a string.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript String replace()
Example: Replace First Occurrence of a Character in a String
// program to replace a character of a string
const string = 'Mr Red has a red house and a red car';
// replace the characters
const newText = string.replace('red', 'blue');
// display the result
console.log(newText);
Output
Mr Red has a blue house and a red car
In the above program, the replace()
method is used to replace the specified string with another string.
When a string is passed in the replace()
method, it replaces only the first instance of the string.
So if there is a second match in the string, it won't be replaced.
You could also pass a regular expression (regex) inside the replace()
method to replace the string.
Example 2: Replace Character of a String Using RegEx
// program to replace a character of a string
const string = 'Mr Red has a red house and a red car';
// regex expression
const regex = /red/g;
// replace the characters
const newText = string.replace(regex, 'blue');
// display the result
console.log(newText);
Output
Mr Red has a blue house and a blue car
In the above program, a regex expression is used as the first parameter inside the replace()
method.
/g
refers to global.
It means that all the matching characters in the string are replaced.
Since JavaScript is case-sensitive, R and r are treated as different values.
You could also use the regex to perform case-insensitive replacement using /gi
, where i
represents case-insensitive.
Reverse a String
In this tutorial, you will learn to write a JavaScript program that reverses a string.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript Function and Function Expressions
Example 1: Reverse a String Using for Loop
// program to reverse a string
function reverseString(str) {
// empty string
let newString = "";
for (let i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
}
// take input from the user
const string = prompt('Enter a string: ');
const result = reverseString(string);
console.log(result);
Output
Enter a string: hello world
dlrow olleh
In the above program, the user is prompted to enter a string.
That string is passed to the reverseString()
function.
Inside the reverseString()
function,
An empty newString variable is created.
The for
loop is used to iterate over the strings.
During the first iteration, str.length - 1
gives the position of the last element.
That element is added to the newString variable.
This process continues for all the string elements.
The value of i decreases in each iteration and continues until it becomes 0.
Example 2: Reverse a String Using built-in Methods
// program to reverse a string
function reverseString(str) {
// return a new array of strings
const arrayStrings = str.split("");
// reverse the new created array elements
const reverseArray = arrayStrings.reverse();
// join all elements of the array into a string
const joinArray = reverseArray.join("");
// return the reversed string
return joinArray;
}
// take input from the user
const string = prompt('Enter a string: ');
const result = reverseString(string);
console.log(result);
Output
Enter a string: hello
olleh
In the above program, the built-in methods are used to reverse a string.
First, the string is split into individual array elements using the split()
method.
str.split("")
gives ["h", "e", "l", "l", "o"].
The string elements are reversed using the reverse()
method.
arrayStrings.reverse()
gives ["o", "l", "l", "e", "h"].
The reversed string elements are joined into a single string using the join()
method.
reverseArray.join("")
gives olleh.
Create Objects in Different Ways
In this example, you will learn to create JavaScript objects in different ways.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Objects
JavaScript Constructor Function
You can create an object in three different ways:
Using object literal
By creating instance of Object directly
By using constructor function
Example 1: Using object literal
// program to create JavaScript object using object literal
const person = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
greet: function() {
console.log('Hello everyone.');
},
score: {
maths: 90,
science: 80
}
};
console.log(typeof person); // object
// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.greet();
console.log(person.score.maths);
Output
object
John
reading
Hello everyone.
90
In this program, we have created an object named person.
You can create an object using an object literal.
An object literal uses { }
to create an object directly.
An object is created with a key:value pair.
You can also define functions, arrays and even objects inside of an object.
You can access the value of the object using dot .
notation.
The syntax for creating an object using instance of an object is:
const objectName = new Object();
Example 2: Create an Object using Instance of Object Directly
// program to create JavaScript object using instance of an object
const person = new Object ( {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
greet: function() {
console.log('Hello everyone.');
},
score: {
maths: 90,
science: 80
}
});
console.log(typeof person); // object
// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.greet();
console.log(person.score.maths);
Output
object
John
reading
Hello everyone.
90
Here, the new
keyword is used with the Object()
instance to create an object.
Example 3: Create an object using Constructor Function
// program to create JavaScript object using instance of an object
function Person() {
this.name = 'John',
this.age = 20,
this.hobbies = ['reading', 'games', 'coding'],
this.greet = function() {
console.log('Hello everyone.');
},
this.score = {
maths: 90,
science: 80
}
}
const person = new Person();
console.log(typeof person); // object
// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.greet();
console.log(person.score.maths);
Output
object
John
reading
Hello everyone.
90
In the above example, the Person()
constructor function is used to create an object using the new
keyword.
new Person()
creates a new object.
Check the Number of Occurrences of a Character in the String
In this example, you will learn to write a JavaScript program that checks the number of occurrences of a character in a string.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript Regex
If you check the number of occurrences of 'o' in the string 'school', the result is 2.
Example 1: Check Occurrence of a Character Using for Loop
// program to check the number of occurrence of a character
function countString(str, letter) {
let count = 0;
// looping through the items
for (let i = 0; i < str.length; i++) {
// check if the character is at that position
if (str.charAt(i) == letter) {
count += 1;
}
}
return count;
}
// take input from the user
const string = prompt('Enter a string: ');
const letterToCheck = prompt('Enter a letter to check: ');
//passing parameters and calling the function
const result = countString(string, letterToCheck);
// displaying the result
console.log(result);
Output
Enter a string: school
Enter a letter to check: o
2
In the above example, the user is prompted to enter a string and the character to check.
In the beginning, the value of the count variable is 0.
The for
loop is used to iterate over the strings.
The charAt()
method returns a character at a specified index.
During each iteration, if the character at that index matches the required character to match, then the count variable is increased by 1.
Example 2: Check occurrence of a character using a Regex
// program to check the occurrence of a character
function countString(str, letter) {
// creating regex
const re = new RegExp(letter, 'g');
// matching the pattern
const count = str.match(re).length;
return count;
}
// take input from the user
const string = prompt('Enter a string: ');
const letterToCheck = prompt('Enter a letter to check: ');
//passing parameters and calling the function
const result = countString(string, letterToCheck);
// displaying the result
console.log(result);
Output
Enter a string: school
Enter a letter to check: o
2
In the above example, a regular expression (regex) is used to find the occurrence of a string.
const re = new RegExp(letter, 'g');
creates a regular expression.
The match()
method returns an array containing all the matches.
Here, str.match(re);
gives ["o", "o"].
The length
property gives the length of an array element.
Convert the First Letter of a String into UpperCase
In this example, you will learn to write a JavaScript program that converts the first letter of a string into uppercase.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
Javascript String toUpperCase()
JavaScript Function and Function Expressions
Example 1: Convert First letter to UpperCase
// program to convert first letter of a string to uppercase
function capitalizeFirstLetter(str) {
// converting first letter to uppercase
const capitalized = str.charAt(0).toUpperCase() + str.slice(1);
return capitalized;
}
// take input
const string = prompt('Enter a string: ');
const result = capitalizeFirstLetter(string);
console.log(result);
Output
Enter a string: javaScript
JavaScript
In the above program, the user is prompted to enter a string and that string is passed into the capitalizeFirstLetter()
function.
The string's first character is extracted using charAt()
method.
Here, str.charAt(0);
gives j.
The toUpperCase()
method converts the string to uppercase.
Here, str.charAt(0).toUpperCase();
gives J.
The slice()
method returns the rest of the string.
Here, str.slice(1);
gives avaScript.
These two values are concatenated using the +
operator.
Note: You can also extract the first character of a string using an array accessing property: str[0]
.
str.str[0]; // j
Example 2: Convert First letter to UpperCase using Regex
// program to convert first letter of a string to uppercase
function capitalizeFirstLetter(str) {
// converting first letter to uppercase
const capitalized = str.replace(/^./, str[0].toUpperCase());
return capitalized;
}
// take input
const string = prompt('Enter a string: ');
const result = capitalizeFirstLetter(string);
console.log(result);
Output
Enter a string: javaScript
JavaScript
In the above program, the regular expression (regex) is used to convert the first letter of a string to uppercase.
The regex pattern is /^./
matches the first character of a string.
The toUpperCase()
method converts the string to uppercase.
Count the Number of Vowels in a String
In this example, you will learn to write a JavaScript program that counts the number of vowels in a string.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
Javascript String match()
Javascript String includes()
The five letters a, e, i, o and u are called vowels.
All other alphabets except these 5 vowels are called consonants.
Example 1: Count the Number of Vowels Using Regex
// program to count the number of vowels in a string
function countVowel(str) {
// find the count of vowels
const count = str.match(/[aeiou]/gi).length;
// return number of vowels
return count;
}
// take input
const string = prompt('Enter a string: ');
const result = countVowel(string);
console.log(result);
Output
Enter a string: JavaScript program
5
In the above program, the user is prompted to enter a string and that string is passed to the countVowel()
function.
The regular expression (RegEx) pattern is used with the match()
method to find the number of vowels in a string.
The pattern /[aeiou]/gi
checks for all the vowels (case-insensitive) in a string.
Here,
str.match(/[aeiou]/gi);
gives ["a", "a", "i", "o", "a"]
The length
property gives the number of vowels present.
Example 2: Count the Number of Vowels Using for Loop
// program to count the number of vowels in a string
// defining vowels
const vowels = ["a", "e", "i", "o", "u"]
function countVowel(str) {
// initialize count
let count = 0;
// loop through string to test if each character is a vowel
for (let letter of str.toLowerCase()) {
if (vowels.includes(letter)) {
count++;
}
}
// return number of vowels
return count
}
// take input
const string = prompt('Enter a string: ');
const result = countVowel(string);
console.log(result);
Output
Enter a string: JavaScript program
5
In the above example,
All the vowels are stored in a vowels
array.
Initially, the value of the count
variable is 0.
The for...of
loop is used to iterate over all the characters of the string.
The toLowerCase()
method converts all the characters of a string to lowercase.
The includes()
method checks if the vowel
array contains any of the characters of the string.
If any character matches, the value of count
is increased by 1.
Remove a Property from an Object
In this example, you will learn to write a JavaScript program that will remove a property from an object.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Objects
An object is written in a key/value pair.
The key/value pair is called a property.
For example,
const student = {
name: 'John',
age: 22
}
Here, name: 'John'
and age: 22
are the two properties of a student object.
Example: Remove a Property From an Object
// program to remove a property from an object
// creating an object
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
greet: function() {
console.log('Hello everyone.');
},
score: {
maths: 90,
science: 80
}
};
// deleting a property from an object
delete student.greet;
delete student['score'];
console.log(student);
Output
{
age: 20,
hobbies: ["reading", "games", "coding"],
name: "John"
}
In the above program, the delete
operator is used to remove a property from an object.
You can use the delete
operator with .
or [ ]
to remove the property from an object.
Note: You should not use the delete operator on predefined JavaScript object properties.
Check Whether a String Starts and Ends With Certain Characters
In this example, you will learn to write a JavaScript program to check whether a string starts and ends with certain characters.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
Javascript String startsWith()
Javascript String endsWith()
JavaScript Regex
Example 1: Check String Using Built-in Methods
// program to check if a string starts with 'S' and ends with 'G'
function checkString(str) {
// check if the string starts with S and ends with G
if(str.startsWith('S') && str.endsWith('G')) {
console.log('The string starts with S and ends with G');
}
else if(str.startsWith('S')) {
console.log('The string starts with S but does not end with G');
}
else if(str.endsWith('G')) {
console.log('The string starts does not with S but end with G');
}
else {
console.log('The string does not start with S and does not end with G');
}
}
// take input
let string = prompt('Enter a string: ');
checkString(string);
Output
Enter a string: String
The string starts with S but does not end with G
In the above program, the two methods startsWith()
and endsWith()
are used.
The startsWith()
method checks if the string starts with the particular string.
The endsWith()
method checks if the string ends with the particular string.
The above program does not check for lowercase letters.
Hence, here G and g are different.
You could also check if the above character starts with S or s and ends with G or g.
str.startsWith('S') || str.startsWith('s') && str.endsWith('G') || str.endsWith('g');
Example 2: Check The String Using Regex
// program to check if a string starts with 'S' and ends with 'G'
function checkString(str) {
// check if the string starts with S and ends with G
if( /^S/i.test(str) && /G$/i.test(str)) {
console.log('The string starts with S and ends with G');
}
else if(/^S/i.test(str)) {
console.log('The string starts with S but does not ends with G');
}
else if(/G$/i.test(str)) {
console.log('The string starts does not with S but ends with G');
}
else {
console.log('The string does not start with S and does not end with G');
}
}
// for loop to show different scenario
for (let i = 0; i < 3; i++) {
// take input
const string = prompt('Enter a string: ');
checkString(string);
}
Output
Enter a string: String
The string starts with S and ends with G
Enter a string: string
The string starts with S and ends with G
Enter a string: JavaScript
The string does not start with S and does not end with G
In the above program, a regular expression (RegEx) is used with the test()
method to check if the string starts with S and ends with G.
The /^S/i
pattern checks if the string is S or s.
Here, i
denotes that the string is case-insensitive.
Hence, S and s are considered the same.
The /G$/i
patterns checks if the string is G or g.
The if...else...if
statement is used to check the conditions and display the outcome accordingly.
The for
loop is used to take different inputs from the user to show different cases.
Check if a Key Exists in an Object
In this example, you will learn to write a JavaScript program that checks if a key exists in an object.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Objects
JavaScript Object hasOwnProperty()
Example 1: Check if Key Exists in Object Using in Operator
// program to check if a key exists
const person = {
id: 1,
name: 'John',
age: 23
}
// check if key exists
const hasKey = 'name' in person;
if(hasKey) {
console.log('The key exists.');
}
else {
console.log('The key does not exist.');
}
Output
The key exists.
In the above program, the in
operator is used to check if a key exists in an object.
The in
operator returns true
if the specified key is in the object, otherwise it returns false
.
Example 2: Check if Key Exists in Object Using hasOwnProperty()
// program to check if a key exists
const person = {
id: 1,
name: 'John',
age: 23
}
//check if key exists
const hasKey = person.hasOwnProperty('name');
if(hasKey) {
console.log('The key exists.');
}
else {
console.log('The key does not exist.');
}
Output
The key exists.
In the above program, the hasOwnProperty()
method is used to check if a key exists in an object.
The hasOwnProperty()
method returns true
if the specified key is in the object, otherwise it returns false
.
Clone a JS Object
In this example, you will learn to write a program that clones an object.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Objects
JavaScript Object.assign()
A JavaScript object is a complex data type that can contain various data types.
For example,
const person = {
name: 'John',
age: 21,
}
Here, person
is an object.
Now, you can't clone an object by doing something like this.
const copy = person;
console.log(copy); // {name: "John", age: 21}
In the above program, the copy
variable has the same value as the person
object.
However, if you change the value of the copy
object, the value in the person
object will also change.
For example,
copy.name = 'Peter';
console.log(copy.name); // Peter
console.log(person.name); // Peter
The change is seen in both objects because objects are reference types.
And both <code>copy</code> and <code>person</code> are pointing to the same object.
Example 1.
Clone the Object Using Object.assign()
// program to clone the object
// declaring object
const person = {
name: 'John',
age: 21,
}
// cloning the object
const clonePerson = Object.assign({}, person);
console.log(clonePerson);
// changing the value of clonePerson
clonePerson.name = 'Peter';
console.log(clonePerson.name);
console.log(person.name);
Output
{name: "John", age: 21}
Peter
John
The Object.assign()
method is part of the ES6 standard.
The Object.assign()
method performs deep copy and copies all the properties from one or more objects.
Note: The empty {}
as the first argument ensures that you don't change the original object.
Example 2: Clone the Object Using Spread Syntax
// program to clone the object
// declaring object
const person = {
name: 'John',
age: 21,
}
// cloning the object
const clonePerson = { ...
person}
console.log(clonePerson);
// changing the value of clonePerson
clonePerson.name = 'Peter';
console.log(clonePerson.name);
console.log(person.name);
Output
{name: "John", age: 21}
Peter
John
The spread syntax ...
was introduced in the later version(ES6).
The spread syntax can be used to make a shallow copy of an object.
This means it will copy the object.
However, the deeper objects are referenced.
For example,
const person = {
name: 'John',
age: 21,
// the inner objects will change in the shallow copy
marks: { math: 66, english: 73}
}
// cloning the object
const clonePerson = { ...
person}
console.log(clonePerson); // {name: "John", age: 21, marks: {…}}
// changing the value of clonePerson
clonePerson.marks.math = 100;
console.log(clonePerson.marks.math); // 100
console.log(person.marks.math); // 100
Here, when the inner object value math
is changed to 100 of clonePerson
object, the value of the math
key of the person
object also changes.
Example 3: Clone the Object Using JSON.parse()
// program to clone the object
// declaring object
const person = {
name: 'John',
age: 21,
}
// cloning the object
const clonePerson = JSON.parse(JSON.stringify(person));
console.log(clonePerson);
// changing the value of clonePerson
clonePerson.name = 'Peter';
console.log(clonePerson.name);
console.log(person.name);
Output
{name: "John", age: 21}
Peter
John
In the above program, the JSON.parse()
method is used to clone an object.
Note: JSON.parse()
only works with Number
and String
object literal.
It does not work with an object literal with function
or symbol
properties.
Loop Through an Object
In this example, you will learn to write a JavaScript program that will loop through an object.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Objects
JavaScript for...in loop
Example 1: Loop Through Object Using for...in
// program to loop through an object using for...in loop
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
// using for...in
for (let key in student) {
let value;
// get the value
value = student[key];
console.log(key + " - " + value);
}
Output
name - John
age - 20
hobbies - ["reading", "games", "coding"]
In the above example, the for...in
loop is used to loop through the student
object.
The value of each key is accessed by using student[key]
.
Note: The for...in
loop will also count inherited properties.
For example,
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
const person = {
gender: 'male'
}
// inheriting property
student.__proto__ = person;
for (let key in student) {
let value;
// get the value
value = student[key];
console.log(key + " - " + value);
}
Output
name - John
age - 20
hobbies - ["reading", "games", "coding"]
gender - male
If you want, you can only loop through the object's own property by using the hasOwnProperty()
method.
if (student.hasOwnProperty(key)) {
++count:
}
Example 2: Loop Through Object Using Object.entries and for...of
// program to loop through an object using for...in loop
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
// using Object.entries
// using for...of loop
for (let [key, value] of Object.entries(student)) {
console.log(key + " - " + value);
}
Output
name - John
age - 20
hobbies - ["reading", "games", "coding"]
In the above program, the object is looped using the Object.entries()
method and the for...of
loop.
The Object.entries()
method returns an array of a given object's key/value pairs.
The for...of
loop is used to loop through an array.
Merge Property of Two Objects
In this example, you will learn to write a JavaScript program that will merge the property of two objects.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Objects
JavaScript Object.assign()
Example 1: Merge Property of Two Objects Using Object.assign()
// program to merge property of two objects
// object 1
const person = {
name: 'Jack',
age:26
}
// object 2
const student = {
gender: 'male'
}
// merge two objects
const newObj = Object.assign(person, student);
console.log(newObj);
Output
{
name: "Jack",
age: 26,
gender: "male"
}
In the above example, two objects are merged into one using the Object.assign()
method.
The Object.assign()
method returns an object by copying the values of all enumerable properties from one or more source objects.
Example 2: Merge Property of Two Objects Using Spread Operator
// program to merge property of two objects
// object 1
const person = {
name: 'Jack',
age:26
}
// object 2
const student = {
gender: 'male'
}
// merge two objects
const newObj = {...person, ...student};
console.log(newObj);
Output
{
name: "Jack",
age: 26,
gender: "male"
}
In the above example, two objects are merged together using the spread operator ...
.
Note: In both the above examples, if the two objects have the same key, then the second object's key overwrites the first object's key.
Count the Number of Keys/Properties in an Object
In this example, you will learn to write a JavaScript program that will count the number of keys/properties in an object.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Objects
JavaScript for...in loop
Javascript Object.keys()
Example 1: Count the Number of Key in an Object Using for...in
// program to count the number of keys/properties in an object
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
let count = 0;
// loop through each key/value
for(let key in student) {
// increase the count
++count;
}
console.log(count);
Output
3
The above program counts the number of keys/properties in an object using the for...in
loop.
The count
variable is initially 0.
Then, the for...in
loop increases the count by 1 for every key/value in an object.
Note: While using the for...in
loop, it will also count inherited properties.
For example,
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
const person = {
gender: 'male'
}
student.__proto__ = person;
let count = 0;
for(let key in student) {
// increase the count
++count;
}
console.log(count); // 4
If you only want to loop through the object's own property, you can use the hasOwnProperty()
method.
if (student.hasOwnProperty(key)) {
++count:
}
Example 2: Count the Number of Key in an Object Using Object.key()
// program to count the number of keys/properties in an object
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
// count the key/value
const result = Object.keys(student).length;
console.log(result);
Output
3
In the above program, the Object.keys()
method and the length
property are used to count the number of keys in an object.
The Object.keys()
method returns an array of a given object's own enumerable property names i.e.
["name", "age", "hobbies"].
The length
property returns the length of the array.
Add Key/Value Pair to an Object
In this example, you will learn to write a JavaScript program that will add a key/value pair to an object.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Objects
Example 1: Add Key/Value Pair to an Object Using Dot Notation
// program to add a key/value pair to an object
const person = {
name: 'Monica',
age: 22,
gender: 'female'
}
// add a key/value pair
person.height = 5.4;
console.log(person);
Output
{
name: "Monica",
age: 22,
gender: "female",
height: 5.4
}
In the above example, we add the new property height
to the person
object using the dot notation .
i.e.
person.height = 5.4;
.
Example 2: Add Key/Value Pair to an Object Using Square Bracket Notation
// program to add a key/value pair to an object
const person = {
name: 'Monica',
age: 22,
gender: 'female'
}
// add a key/value pair
person['height'] = 5.4;
console.log(person);
Output
{
name: "Monica",
age: 22,
gender: "female",
height: 5.4
}
In the above example, we add the new property height
to the person
object using the square bracket notation []
i.e.
person['height'] = 5.4;
.
Replace All Occurrences of a String
In this example, you will learn to write a JavaScript program that will replace all occurrences of a string.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript Regex
Example 1: Replace All Occurrence of String Using RegEx
// program to replace all occurrence of a string
const string = 'Mr Red has a red house and a red car';
// regex expression
const regex = /red/gi;
// replace the characters
const newText = string.replace(regex, 'blue');
// display the result
console.log(newText);
Output
Mr blue has a blue house and a blue car
In the above program, a regex expression is used as the first parameter inside the replace()
method.
/g
refers to global (that replacement is done across the whole string) and /i
refers to case-insensitive.
The replace()
method takes the string that you want to replace as the first parameter and the string you want to replace with as the second parameter.
Example 2: Replace All Occurrence of String Using built-in Method
// program to replace all occurrence of a string
const string = 'Mr red has a red house and a red car';
const result = string.split('red').join('blue');
console.log(result);
Output
Mr blue has a blue house and a blue car
In the above program, the built-in split()
and join()
method is used to replace all the occurrences of the string.
The string is split into individual array elements using the split()
method.
Here, string.split('red')
gives ["Mr ", " has a ", " house and a ", " car"] by splitting the string.
The array elements are joined into a single string using the join()
method.
Here, reverseArray.join('blue')
gives Mr blue has a blue house and a blue car by joining the array elements.
Create Multiline Strings
In this example, you will learn to write a JavaScript program that will create multiline strings.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript Template Literals (Template Strings)
Example 1: Create Multiline Strings Using +
// program to create a multiline strings
// using the + operator
const message = 'This is a long message\n' +
'that spans across multiple lines\n' +
'in the code.'
console.log(message);
Output
This is a long message
that spans across multiple lines
in the code.
In the above example, a multiline string is created using the +
operator and \n
.
The escape character \n
is used to break the line.
Example 2: Create Multiline Strings Using \
// program to create a multiline strings
// using the \ operator
const message = 'This is a long message\n \
that spans across multiple lines\n \
in the code.'
console.log(message);
Output
This is a long message
that spans across multiple lines
in the code.
In the above example, a multiline string is created using \
.
\n
is used to break the line.
Example 3: Create Multiline Strings Using Template Literal
// program to create a multiline strings
// using the template literal
const message = `This is a long message
that spans across multiple lines
in the code.`
console.log(message);
Output
This is a long message
that spans across multiple lines
in the code.
In the above example, the template literal ` `
is used to write multiline strings.
The template literal was introduced in the newer version of JavaScript (ES6).
Some browsers may not support the use of template literals.
To learn more, visit JavaScript Template Literal Support.
Format Numbers as Currency Strings
In this example, you will learn to write a JavaScript program that will format numbers as currency strings.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Number
JavaScript String
Javascript Number toLocaleString()
Example 1: Format Numbers as Currency String
// program to format numbers as currency string
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
formatter.format(2500);
Output
$2,500.00
In the above program, we have used the Intl.NumberFormat
object.
The Intl.NumberFormat
object enables language-sensitive number formatting.
Example 2: Format Numbers as Currency String Using concatenation
// program to format numbers as currency string
const number = 1234.5678;
const result = '$ ' + number.toFixed(2);
console.log(result);
Output
$ 1234.57
In the above example, the toFixed(2)
method is used to round up the number to two decimal values.
'$'
is added to the number to convert it into a currency string.
Example 3: Format Numbers as Currency String Using toLocaleString()
// program to format numbers as currency string
const result = (2500).toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
});
console.log(result);
Output
$2,500.00
The toLocaleString()
method returns a string with a language-sensitive representation of that number.
Example 4: Format Numbers as Currency String Using RegEx
// program to format numbers as currency string
const result = 1234.5678.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
console.warn('$ ' + result);
Output
$ 1,234.57
In the above example, the replace()
method is used with the RegEx pattern to replace the number to currency string.
The toFixed(2)
method is used to round up the number to two decimal values.
Generate Random String
In this example, you will learn to write a JavaScript program that will generate strings of any size by picking characters randomly from A-Z, a-z, and 0-9.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript Math random()
Example 1: Generate Random Strings
// program to generate random strings
// declare all characters
const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
function generateString(length) {
let result = ' ';
const charactersLength = characters.length;
for ( let i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(generateString(5));
Output
B5cgH
In the above example, the Math.random()
method is used to generate random characters from the specified characters (A-Z, a-z, 0-9).
The for
loop is used to loop through the number passed into the generateString()
function.
During each iteration, a random character is generated.
Example 2: Generate Random Strings Using Built-in Methods
// program to generate random strings
const result = Math.random().toString(36).substring(2,7);
console.log(result);
Output
gyjvo
In the above example, built-in methods are used to generate random characters.
The Math.random()
method generates the random number between 0 and 1.
In toString(36)
method, 36 represents base 36.
The toString(36)
represents digits beyond 9 by letters.
The substring(2, 7)
method returns five characters.
Note: In the above examples, the output varies each time because random characters are generated at every execution.
Check if a String Starts With Another String
In this example, you will learn to write a JavaScript program that will check if a string starts with another string.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
Javascript String startsWith()
JavaScript String lastIndexOf()
JavaScript Regex
Example 1: Using startsWith()
// program to check if a string starts with another string
const string = 'hello world';
const toCheckString = 'he';
if(string.startsWith(toCheckString)) {
console.warn('The string starts with "he".');
}
else {
console.warn(`The string does not starts with "he".`);
}
Output
The string starts with "he".
In the above program, the startsWith()
method is used to determine if the string starts with 'he'.
The startsWith()
method checks if the string starts with the particular string.
The if...else
statement is used to check the condition.
Example 2: Using lastIndexOf()
// program to check if a string starts with another string
const string = 'hello world';
const toCheckString = 'he';
let result = string.lastIndexOf(toCheckString, 0) === 0;
if(result) {
console.warn('The string starts with "he".');
}
else {
console.warn(`The string does not starts with "he".`);
}
Output
The string starts with "he".
In the above program, the lastIndexOf()
method is used to check if a string starts with another string.
The lastIndexOf()
method returns the index of the searched string (here searching from the first index).
Example 3: Using RegEx
// program to check if a string starts with another string
const string = 'hello world';
const pattern = /^he/;
let result = pattern.test(string);
if(result) {
console.warn('The string starts with "he".');
}
else {
console.warn(`The string does not starts with "he".`);
}
Output
The string starts with "he".
In the above program, the string is checked using the RegEx pattern and the test()
method.
/^
indicates the starting of the string.
Trim a String
In this example, you will learn to write a JavaScript program that will trim a string.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript String trim()
JavaScript Regex
Example 1: Trim a String
// program to trim a string
const string = ' Hello World ';
const result = string.trim();
console.log(result);
Output
Hello World
In the above example, the trim()
method is used to trim a string.
The trim()
method removes white space from both sides of the string.
Example 2: Trim a String Using RegEx
// program to trim a string
function trimString(x) {
let trimValue = x.replace(/^\s+|\s+$/g,'');
return trimValue;
}
const result = trimString(' Hello world ');
console.log(result);
Output
Hello World
In the above program, the RegEx is used with the replace()
method to trim the string.
/^\s+|\s+$/g
checks for whitespace at the beginning and end of the string.
Convert Objects to Strings
In this example, you will learn to write a JavaScript program that will convert objects to strings.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript and JSON
Example 1: Convert Object to String Using JSON.stringify()
// program to convert an object to a string
const person = {
name: 'Jack',
age: 27
}
const result = JSON.stringify(person);
console.log(result);
console.log(typeof result);
Output
{"name":"Jack","age":27}
string
In the above example, the JSON.stringify()
method is used to convert an object to a string.
The typeof
operator gives the data type of the result variable.
Example 2: Convert Object to String Using String()
// program to convert an object to a string
const person = {
name: 'Jack',
age: 27
}
const result1 = String(person);
const result2 = String(person['name']);
console.log(result1);
console.log(result2);
console.log(typeof result1);
Output
[object Object]
Jack
string
In the above example, the String()
function converts the value of an object to a string.
When using the String()
function on an Object
, the converted result will give [object Object].
The typeof
operator gives the data type of the result variable.
Check Whether a String Contains a Substring
In this example, you will learn to write a JavaScript program that will check if a string contains a substring.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
Javascript String includes()
JavaScript String indexOf()
Example 1: Check String with includes()
// program to check if a string contains a substring
// take input
const str = prompt('Enter a string:');
const checkString = prompt('Enter a string that you want to check:');
// check if string contains a substring
if(str.includes(checkString)) {
console.log(`The string contains ${checkString}`);
} else {
console.log(`The string does not contain ${checkString}`);
}
Output
Enter a string: JavaScript is fun
Enter a string that you want to check: fun
The string contains fun
The includes()
method is used with the if...else
statement to check whether a string contains the characters of a specified string.
Note: The includes()
method is case-sensitive.
Hence, fun and Fun are different.
Example 2: Check String with indexOf()
// program to check if a string contains a substring
// take input
const str = prompt('Enter a string:');
const checkString = prompt('Enter a string that you want to check:');
// check if string contains a substring
if(str.indexOf(checkString) !== -1) {
console.log(`The string contains ${checkString}`);
} else {
console.log(`The string does not contain ${checkString}`);
}
Output
Enter a string: JavaScript is fun
Enter a string that you want to check: fun
The string contains fun
In the above program, the indexOf()
method is used with the if...else
statement to check if a string contains a substring.
The indexOf()
method searches a string and returns the position of the first occurrence.
When a substring cannot be found, it returns -1.
Note: The indexOf()
method is case sensitive.
Compare Two Strings
In this example, you will learn to write a JavaScript program to compare two strings using various methods.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
Javascript String toUpperCase()
JavaScript Regex
Javascript String localeCompare()
Example 1: Using toUpperCase()
// js program to perform string comparison
const string1 = 'JavaScript Program';
const string2 = 'javascript program';
// compare both strings
const result = string1.toUpperCase() === string2.toUpperCase();
if(result) {
console.log('The strings are similar.');
} else {
console.log('The strings are not similar.');
}
Output
The strings are similar.
In the above program, two strings are compared.
Here,
The toUpperCase()
method converts all the string characters to uppercase.
===
is used to check if both the strings are the same.
The if...else
statement is used to display the result as per the condition.
Note: You can also use the toLowerCase()
method to convert all the strings to lowercase and perform the comparison.
Example 2: JS String Comparison Using RegEx
// program to perform string comparison
const string1 = 'JavaScript Program';
const string2 = 'javascript program';
// create regex
const pattern = new RegExp(string1, "gi");
// compare the stings
const result = pattern.test(string2)
if(result) {
console.log('The strings are similar.');
} else {
console.log('The strings are not similar.');
}
Output
The strings are similar.
In the above program, the RegEx is used with the test()
method to perform case insensitive string comparison.
In the RegEx pattern, "g" syntax denotes global and "gi" syntax denotes case insensitive comparisons.
Example 3: Using localeCompare()
// program to perform case insensitive string comparison
const string1 = 'JavaScript Program';
const string2 = 'javascript program';
const result = string1.localeCompare(string2, undefined, { sensitivity: 'base' });
if(result == 0) {
console.log('The strings are similar.');
} else {
console.log('The strings are not similar.');
}
Output
The strings are similar.
In the above program, the localeCompare()
method is used to perform case insensitive string comparison.
The localeCompare()
method returns a number that indicates whether a reference string comes before, or after, or is the same as the given string.
Here, { sensitivity: 'base' }
treats A and a as the same.
Encode a String to Base64
In this example, you will learn to write a JavaScript program that will encode a string to Base64.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.
Example 1: Encode a String to Base64 Using btoa()
// program to encode a string to Base64
// defining the string
const str = "Learning JavaScript";
// encoding the string
const result = window.btoa(str);
console.log(result);
// decoding the string
const result1 = window.atob(result);
console.log(result1);
Output
TGVhcm5pbmcgSmF2YVNjcmlwdA==
Learning JavaScript
In the above example, the btoa()
method is used to convert the string to Base64.
The atob()
method is used to convert the Base64 to a string.
Example 2: Encode a String to Base64 Using Base64 Object
// program to encode a string to Base64
// create Base64 Object
const Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
let output = "";
let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
let i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
let output = "";
let chr1, chr2, chr3;
let enc1, enc2, enc3, enc4;
let i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
let utftext = "";
for (let n = 0; n < string.length; n++) {
let c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
let string = "";
let i = 0;
let c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
// define the string
const string = 'Learning JavaScript';
// encode the String
const encodedString = Base64.encode(string);
console.log(encodedString);
// decode the String
const decodedString = Base64.decode(encodedString);
console.log(decodedString);
Output
TGVhcm5pbmcgSmF2YVNjcmlwdA==
Learning JavaScript.
The encode()
method encodes a string to Base64.
The decode()
method decodes the Base64 to a string.
Replace all Instances of a Character in a String
In this example, you will learn to write a JavaScript program that will replace all instances of a character in a string.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript Regex
JavaScript String split()
Javascript Array join()
Example 1: Replace All Instances Of a Character Using Regex
// program to replace all instances of a character in a string
const string = 'Learning JavaScript Program';
const result = string.replace(/a/g, "A");
console.log(result);
Output
LeArning JAvAScript ProgrAm
In the above example, the RegEx is used with the replace()
method to replace all the instances of a character in a string.
/g
represents that the operation is carried out for all in instances of the string.
Example 2: Replace All Instances Of Character Using Built-in Methods
// program to replace all instances of character in a string
const string = 'Learning JavaScript Program';
const splitString = string.split('a');
const result = splitString.join('A');
console.log(result);
Output
LeArning JAvAScript ProgrAm
In the above example, the built-in methods are used to replace all the occurrences of a character in a string.
The split('a')
method splits the string into an array.
["Le", "rning J", "v", "Script Progr", "m"]
The join('A')
method joins all the array elements into a string by adding A between each array element.
LeArning JAvAScript ProgrAm
Replace All Line Breaks with <br>
In this example, you will learn to write JavaScript program that will replace all line breaks in a string with the <br> tag.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String
JavaScript String replace()
JavaScript String split()
Javascript Array join()
Example 1: Replace All Line Breaks Using RegEx
// program to replace all line breaks in a string with <br>
const string = `I am Learning JavaScript.
JavaScript is fun.
JavaScript is easy.`;
const result = string.replace(/(\r\n|\r|\n)/g, '<br>');
console.log(result);
Output
I am Learning JavaScript.<br>JavaScript is fun.<br>JavaScript is easy.
In the above example:
The RegEx is used with the replace()
method to replace all the line breaks in string with <br>.
The pattern /(\r\n|\r|\n)/
checks for line breaks.
The pattern /g
checks across all the string occurrences.
Example 2: Replace All Line Breaks Using Built-in Methods
// program to replace all line breaks in a string with <br>
const string = `I am Learning JavaScript.
JavaScript is fun.
JavaScript is easy.`;
const result = string.split('\n').join('<br>');
console.log(result);
Output
I am Learning JavaScript.<br>JavaScript is fun.<br>JavaScript is easy.
In the above example, the built-in methods are used to replace all line breaks with <br>.
The split('\n')
splits the string into array elements by splitting on a line break.
["I am Learning JavaScript.", "JavaScript is fun.", "JavaScript is easy."]
The join('<br>')
method joins the array by adding <br>
between array elements.
I am Learning JavaScript.<br>JavaScript is fun.<br>JavaScript is easy.
Display Date and Time
In this example, you will learn to write a JavaScript program that will display date and time.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Date and Time
Example : Display Date and Time
// program to display the date and time
// get date and time
const date = new Date(2017, 2, 12, 9, 25, 30);
// get the date as a string
const n = date.toDateString();
// get the time as a string
const time = date.toLocaleTimeString();
// display date
console.log('Date: ' + n);
// display time
console.log('Time: ' + time);
Output
Date: Sun Mar 12 2017
Time: 9:25:30 AM
In the above example, the new Date()
constructor is used to create a date object.
It gives the date and time according to the given arguments:
const date = new Date(2017, 2, 12, 9, 25, 30);
console.log(date); // Sun Mar 12 2017 09:25:30 GMT+0545 (+0545)
Note: The six numbers in new Date()
specify year, month, day, hour, minute, second respectively.
Also, the month starts from 0.
Hence, January is 0 and December is 11.
The toDateString()
method returns the date portion of a Date
object.
The toLocaleTimeString()
method returns the time portion of a Date
object.
Check Leap Year
In this example, you will learn to write a JavaScript program that will check if a year is leap year or not.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Date and Time
JavaScript if...else Statement
A year is a leap year if the following conditions are satisfied:
The year is a multiple of 400.
The year is a multiple of 4 and not a multiple of 100.
Example 1: Check Leap Year Using if...else
// program to check leap year
function checkLeapYear(year) {
//three conditions to find out the leap year
if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) {
console.log(year + ' is a leap year');
} else {
console.log(year + ' is not a leap year');
}
}
// take input
const year = prompt('Enter a year:');
checkLeapYear(year);
Output
Enter a year: 2000
2000 is a leap year
In the above program, the three conditions are checked to determine if the year is a leap year or not.
The %
operator returns the remainder of the division.
Example 2: Check Leap Year Using newDate()
// program to check leap year
function checkLeapYear(year) {
const leap = new Date(year, 1, 29).getDate() === 29;
if (leap) {
console.log(year + ' is a leap year');
} else {
console.log(year + ' is not a leap year');
}
}
// take input
const year = prompt('Enter a year:');
checkLeapYear(year);
Output
Enter a year: 2000
2000 is a leap year
In the above program, the month of February is checked if it contains 29 days.
If a month of February contains 29 days, it will be a leap year.
The new Date(2000, 1, 29)
gives the date and time according to the specified arguments.
Tue Feb 29 2000 00:00:00 GMT+0545 (+0545)
The getDate()
method returns the day of the month.
Format the Date
In this example, you will learn to write a JavaScript program that will format a date.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript if...else Statement
JavaScript Date and Time
Example 1: Format The Date
// program to format the date
// get current date
let currentDate = new Date();
// get the day from the date
let day = currentDate.getDate();
// get the month from the date
// + 1 because month starts from 0
let month = currentDate.getMonth() + 1;
// get the year from the date
let year = currentDate.getFullYear();
// if day is less than 10, add 0 to make consistent format
if (day < 10) {
day = '0' + day;
}
// if month is less than 10, add 0
if (month < 10) {
month = '0' + month;
}
// display in various formats
const formattedDate1 = month + '/' + day + '/' + year;
console.log(formattedDate1);
const formattedDate2 = month + '-' + day + '-' + year;
console.log(formattedDate2);
const formattedDate3 = day + '-' + month + '-' + year;
console.log(formattedDate3);
const formattedDate4 = day + '/' + month + '/' + year;
console.log(formattedDate4);
Output
08/26/2020
08-26-2020
26-08-2020
26/08/2020
In the above example,
1.
The new Date()
object gives the current date and time.
let currentDate = new Date();
console.log(currentDate);
// Output
// Wed Aug 26 2020 10:45:25 GMT+0545 (+0545)
2.
The getDate()
method returns the day from the specified date.
let day = currentDate.getDate();
console.log(day); // 26
3.
The getMonth()
method returns the month from the specified date.
let month = currentDate.getMonth() + 1;
console.log(month); // 8
4.
1 is added to the getMonth()
method because month starts from 0.
Hence, January is 0, February is 1, and so on.
5.
The getFullYear()
returns the year from the specified date.
let year = currentDate.getFullYear();
console.log(year); // 2020
Then you can display the date in different formats.
Display Current Date
In this example, you will learn to write a JavaScript program that will display the current date.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Date and Time
Example : Display Current Date
// program to display the date
// get local machine date time
const date = new Date();
// get the date as a string
const n = date.toDateString();
// get the time as a string
const time = date.toLocaleTimeString();
// display date
console.log('Date: ' + n);
// display time
console.log('Time: ' + time);
Output
Date: Wed Aug 26 2020
Time: 1:13:12 PM
In the above example, the new Date()
constructor is used to create a date object.
Then,
1.
The new Date()
gives the current date and time.
const date = new Date();
console.log(date);
// Sun Aug 23 2020 10:46:38 GMT+0545 (+0545)
2.
The toDateString()
method returns the date portion of a date object.
const n = date.toDateString();
console.log(n); // Wed Aug 26 2020
3.
The toLocaleTimeString()
method returns the time portion of a date object.
const time = date.toLocaleTimeString();
console.log(time); // 1:13:12 PM
Compare The Value of Two Dates
In this example, you will learn to write a JavaScript program that will compare the values of two dates.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Comparison and Logical Operators
JavaScript Date and Time
Example: Compare Value of Two Dates
// program to compare value of two dates
// create two dates
const d1 = new Date();
const d2 = new Date();
// comparisons
const compare1 = d1 < d2;
console.log(compare1);
const compare2 = d1 > d2;
console.log(compare2);
const compare3 = d1 <= d2;
console.log(compare3);
const compare4 = d1 >= d2;
console.log(compare4);
const compare5 = d1.getTime() === d2.getTime();
console.log(compare5);
const compare6 = d1.getTime() !== d2.getTime();
console.log(compare6);
Output
false
false
true
true
true
false
In the above example, the new Date()
constructor is used to create a date object.
The new Date()
gives the current date and time.
const d1 = new Date();
console.log(d1); // Fri Aug 28 2020 09:19:40 GMT+0545 (+0545)
You can then directly compare these two dates using comparison operators >
, <
, <=
, or >=
.
However, to use comparison operators like ==
, !=
, ===
, or !==
, you have to use date.getTime()
.
The getTime()
method returns the number of milliseconds from midnight of January 1, 1970 (EcmaScript epoch) to the specified date.
const d1 = new Date().getTime();
console.log(d1); // 1598585951699
Create Countdown Timer
In this example, you will learn to write a JavScript program that will create a countdown timer.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Math floor()
JavaScript Date and Time
Javascript setInterval()
Example: Create a Countdown Timer
// program to create a countdown timer
// time to countdown from (in milliseconds)
let countDownDate = new Date().getTime() + 24 * 60 * 60 * 1000;
// countdown timer
let x = setInterval(function() {
// get today's date and time in milliseconds
let now = new Date().getTime();
// find the interval between now and the countdown time
let timeLeft = countDownDate - now;
// time calculations for days, hours, minutes and seconds
const days = Math.floor( timeLeft/(1000*60*60*24) );
const hours = Math.floor( (timeLeft/(1000*60*60)) % 24 );
const minutes = Math.floor( (timeLeft/1000/60) % 60 );
const seconds = Math.floor( (timeLeft/1000) % 60 );
// display the result in the element with id="demo"
console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");
// clearing countdown when complete
if (timeLeft < 0) {
clearInterval(x);
console.log('CountDown Finished');
}
}, 2000);
Output
0d 23h 59m 57s
0d 23h 59m 55s
0d 23h 59m 53s
0d 23h 59m 51s
...
In the above program, the setInterval()
method is used to create a timer.
The setInterval()
method is executed at a given interval time (here, 2000 milliseconds).
The new Date()
gives the current date and time.
For example,
let d1 = new Date();
console.log(time); // Fri Aug 28 2020 09:19:40 GMT+0545 (+0545)
The getTime()
method returns the number of milliseconds from midnight of January 1, 1970 (EcmaScript epoch) to the specified date (here, current date).
The following code gives the next day's time in milliseconds.
new Date().getTime() + 24 * 60 * 60 * 1000;
Now, we can calculate time left using the following formula:
let timeLeft = countDownDate - now;
The remaining number of day is calculated using:
The time interval is divided by 1000 to determine the number of seconds, i.e.
timeLeft / 1000
The time interval then is divided by 60 * 60 * 24 to determine the number of days remaining.
The Math.floor()
function is used to round the number to a whole number.
Similar methods are used for hours, minutes, and seconds.
Note: You can also use a custom starting countdown time by passing a specific date.
For example,
let countDownDate = new Date("Aug 5, 2025 14:22:36").getTime();
Remove Specific Item From an Array
In this example, you will learn to write a JavaScript program that will remove a specific item from an array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array push()
JavaScript Array splice()
JavaScript for loop
Example 1: Using For Loop
// program to remove item from an array
function removeItemFromArray(array, n) {
const newArray = [];
for ( let i = 0; i < array.length; i++) {
if(array[i] !== n) {
newArray.push(array[i]);
}
}
return newArray;
}
const result = removeItemFromArray([1, 2, 3 , 4 , 5], 2);
console.log(result);
Output
[1, 3, 4, 5]
In the above program, an item is removed from an array using a for
loop.
Here,
The for
loop is used to loop through all the elements of an array.
While iterating through the elements of the array, if the item to remove does not match with the array element, that element is pushed to newArray.
The push()
method adds the element to newArray.
Example 2: Using Array.splice()
// program to remove item from an array
function removeItemFromArray(array, n) {
const index = array.indexOf(n);
// if the element is in the array, remove it
if(index > -1) {
// remove item
array.splice(index, 1);
}
return array;
}
const result = removeItemFromArray([1, 2, 3 , 4, 5], 2);
console.log(result);
Output
[1, 3, 4, 5]
In the above program, an array and the element to be removed is passed to the custom removeItemFromArray()
function.
Here,
const index = array.indexOf(2);
console.log(index); // 1
The indexOf()
method returns the index of the given element.
If the element is not in the array, indexOf()
returns -1.
The if
condition checks if the element to remove is in the array.
The splice()
method is used to remove the element from an array.
Note: The above program only works for arrays without duplicate elements.
Only the first element of an array that matches is removed.
For example,
[1, 2, 3, 2, 5]
results in [1, 3, 2, 5]
Check if An Array Contains a Specified Value
In this example, you will learn to write a JavaScript program that will check if an array contains a specified value.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array includes()
JavaScript Array indexOf()
JavaScript Arrays
Example 1: Check Array Using includes()
// program to check if an array contains a specified value
const array = ['you', 'will', 'learn', 'javascript'];
const hasValue = array.includes('javascript');
// check the condition
if(hasValue) {
console.log('Array contains a value.');
} else {
console.log('Array does not contain a value.');
}
Output
Array contains a value.
In the above program, the includes()
method is used to check if an array contains a specified value.
The includes()
method returns true
if the value exists in the array.
The if...else
statement is used to display the result as per the condition.
Example 2: Check Array Using indexOf()
// program to check if an array contains a specified value
const array = ['you', 'will', 'learn', 'javascript'];
const hasValue = array.indexOf('javascript') !== -1;
// check the condition
if(hasValue) {
console.log('Array contains a value.');
} else {
console.log('Array does not contain a value.');
}
Output
Array contains a value.
In the above program, the indexOf()
method is used with the if...else
statement to check if an array contains a specified value.
The indexOf()
method searches an array and returns the position of the first occurrence.
If the value cannot be found, it returns -1.
Note: Both includes()
and indexOf()
are case sensitive.
Hence, J and j are different.
Insert Item in an Array
In this example, you will learn to write a JavaScript program that will insert an item at a specific index into an array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array splice()
JavaScript for loop
JavaScript Arrays
Example 1: Add Item to Array Using splice()
// program to insert an item at a specific index into an array
function insertElement() {
let array = [1, 2, 3, 4, 5];
// index to add to
let index = 3;
// element that you want to add
let element = 8;
array.splice(index, 0, element);
console.log(array);
}
insertElement();
Output
[1, 2, 3, 8, 4, 5]
In the above program, the splice()
method is used to insert an item with a specific index into an array.
The splice()
method adds and/or removes an item.
In the splice()
method,
The first argument specifies the index where you want to insert an item.
The second argument (here 0) specifies the number of items to remove.
The third argument specifies the element that you want to add to an array.
Example 2: Add Item to Array Using for Loop
// program to insert an item at a specific index into an array
function insertElement() {
let array = [1, 2, 3, 4];
// index to add to
let index = 3;
// element that you want to add
let element = 8;
for (let i = array.length; i > index; i--) {
//shift the elements that are greater than index
array[i] = array[i-1];
}
// insert element at given index
array[index] = element;
console.log(array);
}
insertElement();
Output
[1, 2, 3, 8, 4]
In the above program,
The for
loop is used to iterate through the array elements.
The element is added to the given index.
All the elements whose index is greater than the given index are shifted one step to the right.
Append an Object to An Array
In this example, you will learn to write a JavaScript program that will append an object to an array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array push()
JavaScript Array splice()
JavaScript Spread Operator
Example 1: Append Object to Array Using push()
// program to append an object to an array
function insertObject(arr, obj) {
// append object
arr.push(obj);
console.log(arr);
}
// original array
let array = [1, 2, 3];
// object to add
let object = {x: 12, y: 8};
// call the function
insertObject(array, object);
Output
[1, 2, 3, {x: 12, y: 8}]
In the above program, the push()
method is used to add an object to an array.
The push()
method adds an item to the end of an array.
Example 2: Append Object to Array Using splice()
// program to append an object to an array
function insertObject(arr, obj) {
// find the last index
let index = arr.length;
// appending object to end of array
arr.splice(index, 0, object);
console.log(arr);
}
// original array
let array = [1, 2, 3];
// object to add
let object = {x: 12, y: 8};
// call the function
insertObject(array, object);
Output
[1, 2, 3, {x: 12, y: 8}]
In the above program, the splice()
method is used to add an object to an array.
The splice()
method adds and/or removes an item.
In the splice()
method,
The first argument represents the index where you want to insert an item.
The second argument represents the number of items to be removed (here, 0).
The third argument represents the element that you want to add to an array.
Example 3: Append Object Using Spread Operator
// program to append an object to an array
function insertObject(arr, obj) {
// append object
arr = [...arr, object];
console.log(arr);
}
// original array
let array = [1, 2, 3];
// object to add
let object = {x: 12, y: 8};
// call the function
insertObject(array, object);
Output
[1, 2, 3, {x: 12, y: 8}]
In the above program, the spread operator ...
is used to add an object to an array.
The spread syntax allows you to copy all the elements to an array.
Then, the object is added to the end of the array.
Check if An Object is An Array
In this example, you will learn to write a JavaScript program that will check if an object is an array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
Javascript Array isArray()
JavaScript Function and Function Expressions
JavaScript Arrays
Example: Check Array Using Array.isArray()
// program to check if an object is an array
function checkObject(arr) {
// check if arr is array
const result = Array.isArray(arr);
if(result) {
console.log(`[${arr}] is an array.`);
}
else {
console.log(`${arr} is not an array.`);
}
}
const array = [1, 2, 3];
// call the function
checkObject(array);
Output
[1,2,3] is an array.
In the above program, the Array.isArray()
method is used to check if an object is an array.
The Array.isArray()
method returns true
if an object is an array, otherwise returns false
.
Note: For an array, the typeof
operator returns an object.
For example,
const arr = [1, 2, 3];
console.log(typeof arr); // object
Empty an Array
In this example, you will learn to write a JavaScript program that will empty an array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Function and Function Expressions
JavaScript Array length
JavaScript Array splice()
Example 1: Empty Array by Substituting New Array
// program to empty an array
function emptyArray(arr) {
// substituting new array
arr = [];
return arr;
}
const array = [1, 2 ,3];
console.log(array);
// call the function
const result = emptyArray(array);
console.log(result);
Output
[1, 2, 3]
[]
In the above program, the value of array is substituted by a new empty array.
Example 2: Empty Array Using splice()
// program to append an object to an array
function emptyArray(arr) {
// substituting new array
arr.splice(0, arr.length);
return arr;
}
const array = [1, 2 ,3];
console.log(array);
// call the function
const result = emptyArray(array);
console.log(result);
Output
[1, 2, 3]
[]
In the above program, the splice()
method is used to remove all the elements of an array.
In the splice()
method,
The first argument is the index of an array to start removing an item from.
The second argument is the number of elements that you want to remove from the index element.
Example 3: Empty Array by Setting Length 0
// program to empty an array
function emptyArray(arr) {
// setting array length to 0
arr.length = 0;
return arr;
}
const array = [1, 2 ,3];
console.log(array);
// call the function
const result = emptyArray(array);
console.log(result);
Output
[1, 2, 3]
[]
In the above program, the length property is used to empty the array.
When setting array.length
to 0, all the elements of the array are removed.
Add Element to Start of an Array
In this example, you will learn to write a JavaScript program that adds a new element at the beginning of an array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array unshift()
JavaScript Array splice()
JavaScript Array concat()
Example 1: Add Element to Array Using unshift()
// program to add element to an array
function addElement(arr) {
// adding new array element
arr.unshift(4);
console.log(arr);
}
const array = [1, 2, 3];
// calling the function
// passing array argument
addElement(array);
Output
[4, 1, 2, 3]
In the above program, the new element is added to the array variable using the unshift()
method.
The unshift()
method adds a new element at the beginning of an array.
Example 2: Add Element to Array Using splice()
// program to add element to an array
function addElement(arr) {
// adding element to array
arr.splice(0, 0, 4);
console.log(arr);
}
const array = [1, 2, 3];
// calling the function
addElement(array);
Output
[4, 1, 2, 3]
In the above program, the splice()
method is used to add a new element to an array.
In the splice()
method,
The first argument is the index of an array where you want to add an element.
The second argument is the number of elements that you want to remove from the index element.
The third argument is the element that you want to add to the array.
Example 3: Add Element to Array Using Spread Operator
// program to add element to an array
function addElement(arr) {
// adding element to array
arr = [4, ...arr];
console.log(arr);
}
const array = [1, 2, 3];
// calling the function
addElement(arr);
Output
[4, 1, 2, 3]
In the above program, the spread operator ...
is used to add a new element to the beginning of an array.
arr = [4, ...arr];
takes first element as 4 and the rest elements are taken from array.
Example 4: Add Element to Array Using concat()
// program to add element to an array
function addElement(arr) {
// adding element to array
arr = [4].concat(arr);
console.log(arr);
}
const array = [1, 2, 3];
// calling the function
addElement(array);
Output
[4, 1, 2, 3]
In the above program, the concat()
method is used to add a new element to an array.
The concat()
method combines two arrays into one.
Remove Duplicates From Array
In this example, you will learn to write a JavaScript program that removes duplicate values from an array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array indexOf()
JavaScript Array push()
Example 1: Using indexOf() and push()
// program to remove duplicate value from an array
function getUnique(arr){
let uniqueArr = [];
// loop through array
for(let i of arr) {
if(uniqueArr.indexOf(i) === -1) {
uniqueArr.push(i);
}
}
console.log(uniqueArr);
}
const array = [1, 2, 3, 2, 3];
// calling the function
// passing array argument
getUnique(array);
Output
[1, 2, 3]
In the above program, the duplicate elements are removed from array.
Here,
The for...of
loop is used to loop through all the elements of an arr array.
The indexOf()
method returns -1 if the element is not in the array.
Hence, during each iteration, if the element equals -1, the element is added to uniqueArr using push()
.
Example 2: Using Set
// program to remove duplicate value from an array
function getUnique(arr){
// removing duplicate
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr);
}
const array = [1, 2, 3, 2, 3];
// calling the function
getUnique(array);
Output
[1, 2, 3]
In the above program, Set
is used to remove duplicate items from an array.
A Set
is a collection of unique values.
Here,
The array is converted to Set
and all the duplicate elements are automatically removed.
The spread syntax ...
is used to include all the elements of the Set
to a new array.
Merge Two Arrays and Remove Duplicate Items
In this example, you will learn to write a JavaScript program that will merge two arrays and remove duplicate items from an array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array concat()
JavaScript Set and WeakSet
JavaScript Spread Operator
Example 1: Using concat() and for Loop
// program to merge and remove duplicate value from an array
function getUniqueAfterMerge(arr1, arr2){
// merge two arrays
let arr = arr1.concat(arr2);
let uniqueArr = [];
// loop through array
for(let i of arr) {
if(uniqueArr.indexOf(i) === -1) {
uniqueArr.push(i);
}
}
console.log(uniqueArr);
}
const array1 = [1, 2, 3];
const array2 = [2, 3, 5]
// calling the function
// passing array argument
getUniqueAfterMerge(array1, array2);
Output
[1, 2, 3, 5]
In the above program, the two array elements are merged together and the duplicate elements are removed.
Here,
The two arrays are merged using the concat()
method.
The for...of
loop is used to loop through all the elements of arr.
The indexOf()
method returns -1 if the element is not in the array.
Hence, during each iteration, if the element equals -1, the element is added to the uniqueArr array using the push()
method.
Example 2: Using Spread Syntax and Set
// program to merge and remove duplicate value from an array
function getUniqueAfterMerge(arr1, arr2){
// merge two arrays
let arr = [...arr1, ...arr2];
// removing duplicate
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr);
}
const array1 = [1, 2, 3];
const array2 = [2, 3, 5]
// calling the function
getUniqueAfterMerge(array1, array2);
Output
[1, 2, 3, 5]
In the above program, two arrays are merged together and Set
is used to remove duplicate items from an array.
The Set
is a collection of unique values.
Here,
Two array elements are merged together using the spread syntax ...
The array is converted to Set
and all the duplicate elements are automatically removed.
The spread syntax ...
is then used to include all the elements of the set back to an array.
Sort Array of Objects by Property Values
In this example, you will learn to write a JavaScript program that will sort an array of objects by property values.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array sort()
JavaScript Arrays
JavaScript Objects
Example 1: Sort Array by Property Name
// program to sort array by property name
function compareName(a, b) {
// converting to uppercase to have case-insensitive comparison
const name1 = a.name.toUpperCase();
const name2 = b.name.toUpperCase();
let comparison = 0;
if (name1 > name2) {
comparison = 1;
} else if (name1 < name2) {
comparison = -1;
}
return comparison;
}
const students = [{name: 'Sara', age:24},{name: 'John', age:24}, {name: 'Jack', age:25}];
console.log(students.sort(compareName));
Output
[{name: "Jack", age: 25},
{name: "John", age: 24},
{name: "Sara", age: 24}]
In the above program, the sort()
method is used to sort an array by the name property of its object elements.
The sort()
method sorts its elements according to the values returned by a custom sort function (compareName in this case).
Here,
The property names are changed to uppercase using the toUpperCase()
method.
If comparing two names results in 1, then their order is changed.
If comparing two names results in -1 or 0, then their order is left as is.
Example 2: Sort Array by Property Age
// program to sort array by property name
function compareAge(a, b) {
return a.age - b.age;
}
const students = [{name: 'Sara', age:24},{name: 'John', age:22}, {name: 'Jack', age:27}];
console.log(students.sort(compareAge));
Output
[{name: "John", age: 22},
{name: "Sara", age: 24},
{name: "Jack", age: 27}]
In the above program, the sort()
method is used to sort an array element by the age property.
To compare the age property of two objects, we can simply subtract them.
If their difference is a negative value, their order is changed.
If their difference is a positive value, the order is left as is.
Create Two Dimensional Array
In this example, you will learn to write a JavaScript program that will create a two dimensional array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript for loop
JavaScript Arrays
JavaScript Function and Function Expressions
Example: Two Dimensional Array Using for Loop
// program to create a two dimensional array
function twoDimensionArray(a, b) {
let arr = [];
// creating two dimensional array
for (let i = 0; i< a; i++) {
for(let j = 0; j< b; j++) {
arr[i] = [];
}
}
// inserting elements to array
for (let i = 0; i< a; i++) {
for(let j = 0; j< b; j++) {
arr[i][j] = j;
}
}
return arr;
}
const x = 2;
const y = 3;
const result = twoDimensionArray(x, y);
console.log(result);
Output
[[0, 1, 2], [0, 1, 2]]
In the above program, the first argument of the twoDimensionArray()
function represents the number of array elements, and the second argument represents the number of array elements inside of each array element.
The first for
loop is used to create a two dimensional array.
[[], []]
The second for
loop iterates over each array element and inserts the elements inside of an array element.
When i = 0, the elements are inserted to the first array element [[0, 1, 2], []].
When i = 1, the elements are inserted to the second array element [[0, 1, 2], [0, 1, 2]].
Extract Given Property Values from Objects as Array
In this example, you will learn to write a JavaScript program that will extract the value of a property as an array from an array of objects.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array push()
JavaScript Array map()
JavaScript Objects
Example 1: Extract Value Using map()
// program to extract value as an array from an array of objects
function extractValue(arr, prop) {
// extract value from property
let extractedValue = arr.map(item => item[prop]);
return extractedValue;
}
const objArray = [{a: 1, b: 2}, {a: 4, b: 5}, {a: 8, b: 9}];
// passing an array of objects and property 'a' to extract
const result = extractValue(objArray, 'a');
console.log(result);
Output
[1, 4, 8]
In the above program, the property's value of key a
is extracted from each object of an array.
The map()
method is used to iterate through all the elements of an array and extract property values of key a
.
Note: You could also use a regular function instead of an arrow function.
let extractedValue = arr.map(function(item) {return item[prop]});
Example 2: Extract Value Using for Loop
// program to extract value as an array from an array of objects
function extractValue(arr, prop) {
let extractedValue = [];
for (let i=0; i < arr.length ; ++i) {
// extract value from property
extractedValue.push(arr[i][prop]);
}
return extractedValue;
}
const objArray = [{a: 1, b: 2}, {a: 4, b: 5}, {a: 8, b: 9}];
// passing an array of objects and property 'a' to extract
const result = extractValue(objArray, 'a');
console.log(result);
Output
[1, 4, 8]
In the above program, the property value of key a
is extracted from each object of an array.
Initially, the extractedValue array is empty.
The for
loop is used to iterate through all the elements of an array.
During each iteration, the value of property a
is pushed to the extractedValue array.
Compare Elements of Two Arrays
In this example, you will learn to write a JavaScript program that will compare the elements of two arrays.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript for loop
JavaScript Arrays
JavaScript Function and Function Expressions
Example 1 : Compare Arrays Using JSON.stringify()
// program to compare two arrays
function compareArrays(arr1, arr2) {
// compare arrays
const result = JSON.stringify(arr1) == JSON.stringify(arr2)
// if result is true
if(result) {
console.log('The arrays have the same elements.');
}
else {
console.log('The arrays have different elements.');
}
}
const array1 = [1, 3, 5, 8];
const array2 = [1, 3, 5, 8];
compareArrays(array1, array2);
Output
The arrays have the same elements.
The JSON.stringify()
method converts an array into JSON string.
JSON.stringify([1, 3, 5, 8]); // "[1,3,5,8]"
Then, the two array strings are compared using ==
.
Example 2: Compare Arrays using for Loop
// program to extract value as an array from an array of objects
function compareArrays(arr1, arr2) {
// check the length
if(arr1.length != arr2.length) {
return false;
}
else {
let result = false;
// comparing each element of array
for(let i=0; i<arr1.length; i++) {
if(arr1[i] != arr2[i]) {
return false;
}
else {
result = true;
}
}
return result;
}
}
const array1 = [1, 3, 5, 8];
const array2 = [1, 3, 5, 8];
const result = compareArrays(array1, array2);
// if result is true
if(result) {
console.log('The arrays have the same elements.');
}
else {
console.log('The arrays have different elements.');
}
Output
The arrays have the same elements.
In the above program,
The length of the array elements are compared using the length
property.
If both arrays have different lengths, false
is returned.
Else,
The for
loop is used to iterate through all the elements of the first array.
During each iteration, elements of the first array are compared to corresponding elements of the second array.
arr1[i] != arr2[i]
If the corresponding array elements of both arrays are not equal, false
is returned and the loop terminates.
If all elements are equal, true
is returned.
Note: The above program does not work if the array element contains objects.
For example,
array1 = [1, {a : 2}, 3, 5];
Get Random Item From an Array
In this example, you will learn to write a JavaScript program that will get a random item from an array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array length
JavaScript Math random()
JavaScript Math floor()
Example: Get Random Item From an Array
// program to get a random item from an array
function getRandomItem(arr) {
// get random index value
const randomIndex = Math.floor(Math.random() * arr.length);
// get random item
const item = arr[randomIndex];
return item;
}
const array = [1, 'hello', 5, 8];
const result = getRandomItem(array);
console.log(result);
Output
'hello'
In the above program, a random item from an array is accessed.
A random number between 0 to array.length is generated using the Math.random()
method.
The Math.floor()
returns the nearest integer value generated by Math.random()
.
This random index is then used to access a random array element.
Perform Intersection Between Two Arrays
In this example, you will learn to write a JavaScript program that will perform an intersection between two arrays.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
Javascript Array filter()
JavaScript Array push()
JavaScript Set and WeakSet
Example 1: Perform Intersection Using Set
// program to perform intersection between two arrays using Set
// intersection contains the elements of array1 that are also in array2
function performIntersection(arr1, arr2) {
// converting into Set
const setA = new Set(arr1);
const setB = new Set(arr2);
let intersectionResult = [];
for (let i of setB) {
if (setA.has(i)) {
intersectionResult.push(i);
}
}
return intersectionResult;
}
const array1 = [1, 2, 3, 5, 9];
const array2 = [1, 3, 5, 8];
const result = performIntersection(array1, array2);
console.log(result);
Output
[1, 3, 5]
In the above program, an intersection is performed between array1
and array2
.
The array elements are converted into Set
elements using the new Set()
constructor.
The for...of
loop is used to iterate over the second Set
elements.
The has()
method is used to check if the element is in the first Set
.
If the element is present in the first Set
, that element is added to the intersectionResult array using the push()
method.
Example 2: Perform Intersection Using filter() Method
// program to perform intersection between two arrays
function performIntersection(arr1, arr2) {
const intersectionResult = arr1.filter(x => arr2.indexOf(x) !== -1);
return intersectionResult;
}
const array1 = [1, 2, 3, 5, 9];
const array2 = [1, 3, 5, 8];
const result = performIntersection(array1, array2);
console.log(result);
Output
[1, 3, 5]
In the above program, an intersection is performed between two arrays using the filter()
method.
The filter method iterates over an array and returns the array elements that pass the given condition.
Each element of the first array is compared with the second array using the indexOf()
method.
The arr2.indexOf(x)
method searches arr2 and returns the position of the first occurrence of arr1.
If the value cannot be found, it returns -1.
All the elements that are in both arrays are returned by the filter()
method.
Note: You could also use the includes()
method to check if the array elements are in both arrays.
const intersectionResult = arr1.filter(x => arr2.includes(x))
Split Array into Smaller Chunks
In this example, you will learn to write a JavaScript program that will split an array into smaller chunks of array.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array slice()
JavaScript Array splice()
JavaScript Arrays
Example 1: Split Array Using slice()
// program to split array into smaller chunks
function splitIntoChunk(arr, chunk) {
for (i=0; i < arr.length; i += chunk) {
let tempArray;
tempArray = arr.slice(i, i + chunk);
console.log(tempArray);
}
}
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const chunk = 2;
splitIntoChunk(array, chunk);
Output
[1, 2]
[3, 4]
[5, 6]
[7, 8]
In the above program, the for
loop is used with the slice()
method to split an array into smaller chunks of array.
The for
loop iterates through the elements of an array.
During each iteration, the value of i is increased by chunk value (here 2).
The slice()
method extracts elements from an array where:
The first argument specifies the starting index.
The second argument specifies the ending index.
Example 2: Split Array Using splice()
// program to split array into smaller chunks
function splitIntoChunk(arr, chunk) {
while(arr.length > 0) {
let tempArray;
tempArray = arr.splice(0, chunk);
console.log(tempArray);
}
}
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const chunk = 2;
splitIntoChunk(array, chunk);
Output
[1, 2]
[3, 4]
[5, 6]
[7, 8]
In the above program, the while loop is used with the splice()
method to split an array into smaller chunks of an array.
In the splice()
method,
The first argument specifies the index where you want to split an item.
The second argument (here 2) specifies the number of items to split.
The while
loop is used to iterate over the array until the array is empty.
Include a JS file in Another JS file
In this example, you will learn to write a JavaScript program that will include a JS file into another JS file.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Variables and Constants
JavaScript Function and Function Expressions
JavaScript Modules
Example: Using import/export
Let's create a file named module.js (filename can be anything) with the following content:
// program to include JS file into another JS file
const message = 'hello world';
const number = 10;
function multiplyNumbers(a, b) {
return a * b;
}
// exporting variables and function
export { message, number, multiplyNumbers };
In order to include these variables and functions in another file, say main.js, you can use the import
keyword as:
// import the variables and function from module.js
import { message, number, multiplyNumbers } from './modules.js';
console.log(message); // hello world
console.log(number); // 10
console.log(multiplyNumbers(3, 4)); // 12
console.log(multiplyNumbers(5, 8)); // 40
To include another file, you have to export the code that you want to use in another file using the export
statement.
For example,
export { message, number, multiplyNumbers };
You could also do individual export.
For example,
export const message = 'hello world';
export const number = 10;
To include code from another file, you have to use the import
statement and import using the file path.
For example,
// importing codes from module file
import { message, number, multiplyNumbers } from './modules.js';
Then, you can use these codes as they are a part of the same file.
This helps in writing cleaner, maintainable, and modular code.
Get File Extension
In this example, you will learn to write a JavaScript program that will get the file extension of a given filename.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String split()
Javascript String substring()
JavaScript String lastIndexOf()
Example 1: Using split() and pop()
// program to get the file extension
function getFileExtension(filename){
// get file extension
const extension = filename.split('.').pop();
return extension;
}
// passing the filename
const result1 = getFileExtension('module.js');
console.log(result1);
const result2 = getFileExtension('module.txt');
console.log(result2);
Output
js
txt
In the above program, the extension of the filename is extracted using the split()
method and the pop()
method.
The filename is split into individual array elements using the split()
method.
Here, filename.split('.')
gives ["module", "js"] by splitting the string.
The last array element, which is the extension, is returned using the pop()
method.
Example 2: Using substring() and lastIndexOf()
// program to get the file extension
function getFileExtension(filename){
// get file extension
const extension = filename.substring(filename.lastIndexOf('.') + 1, filename.length);
return extension;
}
const result1 = getFileExtension('module.js');
console.log(result1);
const result2 = getFileExtension('test.txt');
console.log(result2);
Output
js
txt
In the above program, the extension of the filename is extracted using the substring()
method and the lastIndexOf()
method.
filename.lastIndexOf('.') + 1
returns the last position of .
in the filename.
1 is added because the position count starts from 0.
The filename.length
property returns the length of the string.
substring(filename.lastIndexOf('.') + 1, filename.length)
method returns characters between the given indexes.
For example, 'module.js'.substring(8, 10)
returns js.
The OR ||
operator is used to return the original string if there is no .
in the filename.
Check If A Variable Is undefined or null
In this example, you will learn to write a JavaScript program that will check if a variable is undefined or null.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript null and undefined
JavaScript typeof Operator
JavaScript Function and Function Expressions
Example 1: Check undefined or null
// program to check if a variable is undefined or null
function checkVariable(variable) {
if(variable == null) {
console.log('The variable is undefined or null');
}
else {
console.log('The variable is neither undefined nor null');
}
}
let newVariable;
checkVariable(5);
checkVariable('hello');
checkVariable(null);
checkVariable(newVariable);
Output
The variable is neither undefined nor null
The variable is neither undefined nor null
The variable is undefined or null
The variable is undefined or null
In the above program, a variable is checked if it is equivalent to null
.
The null
with ==
checks for both null
and undefined
values.
This is because null == undefined
evaluates to true.
The following code:
if(variable == null) { ...
}
is equivalent to
if (variable === undefined || variable === null) { ...
}
Example 2: using typeof
// program to check if a variable is undefined or null
function checkVariable(variable) {
if( typeof variable === 'undefined' || variable === null ) {
console.log('The variable is undefined or null');
}
else {
console.log('The variable is neither undefined nor null');
}
}
let newVariable;
checkVariable(5);
checkVariable('hello');
checkVariable(null);
checkVariable(newVariable);
Output
The variable is neither undefined nor null
The variable is neither undefined nor null
The variable is undefined or null
The variable is undefined or null
The typeof
operator for undefined
value returns undefined.
Hence, you can check the undefined
value using typeof
operator.
Also, null
values are checked using the ===
operator.
Note: We cannot use the typeof
operator for null
as it returns object.
Set a Default Parameter Value For a Function
In this example, you will learn to write a JavaScript program that will set a default parameter value for a function.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Function and Function Expressions
JavaScript Default Parameters
The syntax to set the default parameter value for a function is:
function functionName(param1=default1, param2=default2, ...) {
// function body
}
Example 1: Set Default Parameter Value For a Function
// program to set default parameter value
function sum(x = 3, y = 5) {
// return sum
return x + y;
}
console.log(sum(5, 15));
console.log(sum(7));
console.log(sum());
Output
20
12
8
In the above example, the default value of x
is 3 and the default value of y
is 5.
sum(5, 15)
- When both arguments are passed, x
takes 5 and y
takes 15.
sum(7)
- When 7 is passed to the sum()
function, x
takes 7 and y
takes the default value 5.
sum()
- When no argument is passed to the sum()
function, x
takes the default value 3 and y
takes the default value 5.
Example 2: Using Previous Parameter in Another Parameter
// using previous parameter in default value expression
let calculate = function(x = 15, y = x + 2) {
return x + y;
}
const result1 = calculate(10);
console.log(result1);
const result2 = calculate();
console.log(result2);
Output
22
32
You can also pass a parameter as the default value for another parameter.
In the above program,
When 10 is passed to the calculate()
function, x
becomes 10, and y
becomes 12 (the sum
function returns 22).
When no value is passed to the calculate()
function, x
becomes 15, and y
becomes 17 (the sum
function returns 32).
Illustrate Different Set Operations
In this example, you will learn to write a JavaScript program that will illustrate different set operations.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Set and WeakSet
JavaScript for...
of Loop
JavaScript Function and Function Expressions
Example 1: Set Union Operation
// perform union operation
// contain elements of both sets
function union(a, b) {
let unionSet = new Set(a);
for (let i of b) {
unionSet.add(i);
}
return unionSet
}
// two sets of fruits
const setA = new Set(['apple', 'mango', 'orange']);
const setB = new Set(['grapes', 'apple', 'banana']);
const result = union(setA, setB);
console.log(result);
Output
Set {"apple", "mango", "orange", "grapes", "banana"}
The set union operation combines elements of both sets into one.
A new set unionSet
is created using new Set()
.
The unionSet variable contains all the values of setA.
Then, the for...of
loop is used to iterate through all the elements of setB and add them to unionSet using the add()
method.
The set does not contain duplicate values.
Hence, if the set contains the same value, the latter value is discarded.
Example 2: Set Intersection Operation
// perform intersection operation
// elements of set a that are also in set b
function intersection(setA, setB) {
let intersectionSet = new Set();
for (let i of setB) {
if (setA.has(i)) {
intersectionSet.add(i);
}
}
return intersectionSet;
}
// two sets of fruits
const setA = new Set(['apple', 'mango', 'orange']);
const setB = new Set(['grapes', 'apple', 'banana']);
const result = intersection(setA, setB);
console.log(result);
Output
Set {"apple"}
The set intersection operation represents elements that are present in both setA and setB.
A new set intersectionSet
is created using new Set()
.
Then, the for...of
loop is used to iterate through the setB.
For every element that is present in both setA and setB, they are added to the intersection set.
Example 3: Set Difference Operation
// perform difference operation
// elements of set a that are not in set b
function difference(setA, setB) {
let differenceSet = new Set(setA)
for (let i of setB) {
differenceSet.delete(i)
}
return differenceSet
}
// two sets of fruits
const setA = new Set(['apple', 'mango', 'orange']);
const setB = new Set(['grapes', 'apple', 'banana']);
const result = difference(setA, setB);
console.log(result);
Output
Set {"mango", "orange"}
The set difference operation represents elements that are present in one set and not in another set.
The differenceSet contains all the elements of setA.
Then, the for...of
loop is used to iterate through all the elements of setB.
If the element that is present in setB is also available in setA, that element is deleted using delete()
method.
Example 4: Set Subset Operation
// perform subset operation
// true if all elements of set b is in set a
function subset(setA, setB) {
for (let i of setB) {
if (!setA.has(i)) {
return false
}
}
return true
}
// two sets of fruits
const setA = new Set(['apple', 'mango', 'orange']);
const setB = new Set(['apple', 'orange']);
const result = subset(setA, setB);
console.log(result);
Output
true
The set subset operation returns true if all the elements of setB are in setA.
The for...of
loop is used to loop through the elements of setB.
If any element that is present is setB is not present in setA, false
is returned.
Generate a Random Number Between Two Numbers
In this example, you will learn to write a JavaScript program that will generate a random number between two numbers.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Math random()
JavaScript Math floor()
JavaScript parseInt()
If you want to find a random integer in between min (inclusive) to max (inclusive), you can use the following formula:
Math.floor(Math.random() * (max - min + 1)) + min
Example: Integer Value Between Two Numbers
// input from the user
const min = parseInt(prompt("Enter a min value: "));
const max = parseInt(prompt("Enter a max value: "));
// generating a random number
const a = Math.floor(Math.random() * (max - min + 1)) + min;
// display a random number
console.log(`Random value between ${min} and ${max} is ${a}`);
Output
Enter a min value: 1
Enter a min value: 50
Random value between 1 and 50 is 47
In JavaScript, you can generate a random number with the Math.random()
function.
Math.random()
returns a random floating-point number ranging from 0 to less than 1 (inclusive of 0 and exclusive of 1)
The above program will show an integer output between min (inclusive) to max (inclusive).
First, the minimum and maximum values are taken as input from the user.
Then the Math.random()
method is used to get the random number from the passed value.
The Math.floor()
returns the nearest integer value.
Get The Current URL
In this example, you will learn to write a JavaScript program that will get the current URL.
Example: Get The Current URL
// program to get the URL
const url1 = window.location.href;
const url2 = document.URL;
console.log(url1);
console.log(url2);
Output
https://www.google.com/
https://www.google.com/
In the above program, window.location.href
property and document.URL
property are used to get the URL of the current page.
Both the window.location.href
and the document.URL
properties return the URL of the current page.
Validate An Email Address
In this example, you will learn to write a JavaScript program that will validate an email address.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Regex
JavaScript Function and Function Expressions
JavaScript if...else Statement
Example: Using Regex
// program to validate an email address
function validateEmail(email_id) {
const regex_pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regex_pattern.test(email_id)) {
console.log('The email address is valid');
}
else {
console.log('The email address is not valid');
}
}
validateEmail('abc123@gmail.com');
validateEmail('hello@com');
Output
The email address is valid
The email address is not valid
In the above program, the regular expression pattern
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
checks if an email address is valid or not.
The test()
method returns true
if there is a match in the string with the regex pattern.
The regular expression (regex) describes a sequence of characters used for defining a search pattern.
To learn more about the regex, visit JavaScript Regular Expression.
Check If a Variable is of Function Type
In this example, you will learn to write a JavaScript program that will check if a variable is of function type.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript typeof Operator
Javascript Function call()
Javascript Object toString()
Example 1: Using instanceof Operator
// program to check if a variable is of function type
function testVariable(variable) {
if(variable instanceof Function) {
console.log('The variable is of function type');
}
else {
console.log('The variable is not of function type');
}
}
const count = true;
const x = function() {
console.log('hello')
};
testVariable(count);
testVariable(x);
Output
The variable is not of function type
The variable is of function type
In the above program, the instanceof
operator is used to check the type of variable.
Example 2: Using typeof Operator
// program to check if a variable is of function type
function testVariable(variable) {
if(typeof variable === 'function') {
console.log('The variable is of function type');
}
else {
console.log('The variable is not of function type');
}
}
const count = true;
const x = function() {
console.log('hello')
};
testVariable(count);
testVariable(x);
Output
The variable is not of function type
The variable is of function type
In the above program, the typeof
operator is used with strict equal to ===
operator to check the type of variable.
The typeof
operator gives the variable data type.
===
checks if the variable is equal in terms of value as well as the data type.
Example 3: Using Object.prototype.toString.call() Method
// program to check if a variable is of function type
function testVariable(variable) {
if(Object.prototype.toString.call(variable) == '[object Function]') {
console.log('The variable is of function type');
}
else {
console.log('The variable is not of function type');
}
}
const count = true;
const x = function() {
console.log('hello')
};
testVariable(count);
testVariable(x);
Output
The variable is not of function type
The variable is of function type
The Object.prototype.toString.call()
method returns a string that specifies the object type.
Work With Constants
In this example, you will learn to write a JavaScript program to work with constants.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Variables and Constants
Example: Work With Constants
// program to include constants
const a = 5;
console.log(a);
// constants are block-scoped
{
const a = 50;
console.log(a);
}
console.log(a);
const arr = ['work', 'exercise', 'eat'];
console.log(arr);
// add elements to arr array
arr[3] = 'hello';
console.log(arr);
// the following code gives error
// changing the value of a throws an error
// uncomment to verify
// a = 8;
// throws an error
// const x;
Output
5
50
5
["work", "exercise", "eat"]
["work", "exercise", "eat", "hello"]
JavaScript ES6 has introduced the const
keyword to work with constants.
const
denotes that the reference to value is constant and cannot be changed.
For example,
const a = 5;
a = 44; // throws an error
Constants are block-scoped.
Hence the variable defined inside a block represents a different value than the one outside.
For example,
{
const a = 50;
console.log(a); // 50
}
console.log(a); // 5
The arr array value is changed and a new element is added.
In array, the values can be changed.
However, the array reference cannot be changed.
For example,
const arr = ['work', 'exercise', 'eat'];
arr[3] = 'hello';
Also, the constant should be initialized.
You cannot just declare a constant.
For example,
const x;
// SyntaxError: const declared variable 'x' must have an initializer.
Pass Parameter to a setTimeout() Function
In this example, you will learn to write a JavaScript program that will pass a parameter to a setTimeout() function.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Function and Function Expressions
Javascript setTimeout()
The setTimeout()
method executes a block of code after the specified time.
The method executes the code only once.
The commonly used syntax of JavaScript setTimeout is:
setTimeout(function, milliseconds);
Its parameters are:
function - a function containing a block of code
milliseconds - the time after which the function is executed
Example 1: Passing Parameter to setTimeout
// program to pass parameter to a setTimeout() function
function greet() {
console.log('Hello world');
}
// passing parameter
setTimeout(greet, 3000);
console.log('This message is shown first');
Output
This message is shown first
Hello world
In the above program, the greet()
function is passed to the setTimeout()
.
The greet()
function then gets called after 3000 milliseconds (3 seconds).
Hence, the program displays the text Hello world only once after 3 seconds.
Example 2: Passing Parameter to Function
//
program to pass parameter to function in setTimeout()
function greet(x, y) {
console.log(x);
console.log(y);
}
// passing parameter
setTimeout(greet, 3000, 'hello', 'world');
console.log('This message is shown first');
Output
This message is shown first
hello
world
In the above program, additional parameters x and y are required in the greet()
function.
When calling the setTimeout()
function, additional arguments 'hello'
and 'world'
are passed which are used by the greet()
function.
Generate a Range of Numbers and Characters
In this example, you will learn to write a JavaScript program that will generate a range of numbers and characters by passing the upper and lower bounds.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String fromCharCode()
JavaScript String charCodeAt()
JavaScript Array map()
JavaScript Generators
Example: Generate Range of Characters
// program to generate range of numbers and characters
function* iterate(a, b) {
for (let i = a; i <= b; i += 1) {
yield i
}
}
function range(a, b) {
if(typeof a === 'string') {
let result = [...iterate(a.charCodeAt(), b.charCodeAt())].map(n => String.fromCharCode(n));
console.log(result);
}
else {
let result = [...iterate(a, b)];
console.log(result);
}
}
range(1, 5);
range('A', 'G');
Output
[1, 2, 3, 4, 5]
["A", "B", "C", "D", "E", "F", "G"]
In the above program, a range of numbers and characters is generated between the upper and the lower bounds.
The iterate
generator function is used to iterate through lower and upper bounds.
The spread syntax ...
is then used to include all the elements returned by the iterate
function.
The charCodeAt()
method takes in an index value and returns an integer representing its UTF-16 (16-bit Unicode Transformation Format) code.
The map()
method iterates through all the array elements.
The fromCharCode()
method converts Unicode values into characters.
Perform Function Overloading
In this example, you will learn to write a JavaScript program that will perform function overloading.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript if...else Statement
JavaScript Switch Statement
JavaScript Function and Function Expressions
In programming, function overloading refers to the concept where multiple functions with the same names can have different implementations.
However, in JavaScript, if there are multiple functions with the same name, the function that is defined at the last gets executed.
The function overloading feature can be implemented in some other ways.
Example 1: Using if/else-if Statement
// program to perform function overloading
function sum() {
// if no argument
if (arguments.length == 0) {
console.log('You have not passed any argument');
}
// if only one argument
else if (arguments.length == 1) {
console.log('Pass at least two arguments');
}
// multiple arguments
else {
let result = 0;
let length = arguments.length;
for (i = 0; i < length; i++) {
result = result + arguments[i];
}
console.log(result);
}
}
sum();
sum(5);
sum(5, 9);
sum(1, 2, 3, 4, 5, 6, 7, 8, 9);
Output
You have not passed any argument
Pass at least two arguments
14
45
In the above program, the overloading feature is accomplished by using the if/else...if
statement.
In JavaScript, the arguments
object is automatically available inside a function that represents the passed arguments to a function.
The multiple conditions are addressed to perform actions based on that particular condition.
Example 2: Using switch Statement
// program to perform function overloading
function sum() {
switch (arguments.length) {
case 0:
console.log('You have not passed any argument');
break;
case 1:
console.log('Pass at least two arguments');
break;
default:
let result = 0;
let length = arguments.length;
for (i = 0; i < length; i++) {
result = result + arguments[i];
}
console.log(result);
break;
}
}
sum();
sum(5);
sum(5, 9);
sum(1, 2, 3, 4, 5, 6, 7, 8, 9);
Output
You have not passed any argument
Pass at least two arguments
14
45
In the above program, the switch
statement is used to accomplish the function overloading functionality.
Different conditions result in different actions to be performed.
Implement a Stack
In this example, you will learn to write a JavaScript program that will implement a stack.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array push()
JavaScript Array pop()
JavaScript Methods and this Keyword
The stack is a data structure that follows Last In First Out (LIFO) principle.
The element that is added at last is accessed at first.
This is like stacking your books on top of each other.
The book that you put at last comes first.
Example: Implement Stack
// program to implement stack data structure
class Stack {
constructor() {
this.items = [];
}
// add element to the stack
add(element) {
return this.items.push(element);
}
// remove element from the stack
remove() {
if(this.items.length > 0) {
return this.items.pop();
}
}
// view the last element
peek() {
return this.items[this.items.length - 1];
}
// check if the stack is empty
isEmpty(){
return this.items.length == 0;
}
// the size of the stack
size(){
return this.items.length;
}
// empty the stack
clear(){
this.items = [];
}
}
let stack = new Stack();
stack.add(1);
stack.add(2);
stack.add(4);
stack.add(8);
console.log(stack.items);
stack.remove();
console.log(stack.items);
console.log(stack.peek());
console.log(stack.isEmpty());
console.log(stack.size());
stack.clear();
console.log(stack.items);
Output
[1, 2, 4, 8]
[1, 2, 4]
4
false
3
[]
In the above program, the Stack
class is created to implement the stack data structure.
The class methods like add()
, remove()
, peek()
, isEmpty()
, size()
, clear()
are implemented.
An object stack is created using a new
operator and various methods are accessed through the object.
Here, initially this.items is an empty array.
The push()
method adds an element to this.items.
The pop()
method removes the last element from this.items.
The length
property gives the length of this.items.
Implement a Queue
In this example, you will learn to write a JavaScript program that will implement a queue.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Array push()
JavaScript Array shift()
JavaScript Methods and this Keyword
A queue is a data structure that follows First In First Out (FIFO) principle.
The element that is added first is accessed at first.
This is like being in a queue to get a movie ticket.
The first one gets the ticket first.
Example: Implement Queue
// program to implement queue data structure
class Queue {
constructor() {
this.items = [];
}
// add element to the queue
enqueue(element) {
return this.items.push(element);
}
// remove element from the queue
dequeue() {
if(this.items.length > 0) {
return this.items.shift();
}
}
// view the last element
peek() {
return this.items[this.items.length - 1];
}
// check if the queue is empty
isEmpty(){
return this.items.length == 0;
}
// the size of the queue
size(){
return this.items.length;
}
// empty the queue
clear(){
this.items = [];
}
}
let queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(4);
queue.enqueue(8);
console.log(queue.items);
queue.dequeue();
console.log(queue.items);
console.log(queue.peek());
console.log(queue.isEmpty());
console.log(queue.size());
queue.clear();
console.log(queue.items);
Output
[1, 2, 4, 8]
[2, 4, 8]
8
false
3
[]
In the above program, the Queue
class is created to implement the queue data structure.
The class includes methods like enqueue()
, dequeue()
, peek()
, isEmpty()
, size()
, and clear()
.
A Queue
object is created using a new
operator and various methods are accessed through the object.
Initially, this.items
is an empty array.
The push()
method adds an element to this.items.
The shift()
method removes the first element from this.items.
The length
property gives the length of this.items.
Check if a Number is Float or Integer
In this example, you will learn to write a JavaScript program that will check if a number is a float or an integer value.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Regex
JavaScript Number.isInteger()
JavaScript typeof Operator
Example 1: Using Number.isInteger()
// program to check if a number is a float or integer value
function checkNumber(x) {
// check if the passed value is a number
if(typeof x == 'number' && !isNaN(x)){
// check if it is integer
if (Number.isInteger(x)) {
console.log(`${x} is integer.`);
}
else {
console.log(`${x} is a float value.`);
}
} else {
console.log(`${x} is not a number`);
}
}
checkNumber('hello');
checkNumber(44);
checkNumber(3.4);
checkNumber(-3.4);
checkNumber(NaN);
Output
hello is not a number
44 is integer.
3.4 is a float value.
-3.4 is a float value.
NaN is not a number
In the above program, the passed value is checked if it is an integer value or a float value.
The typeof
operator is used to check the data type of the passed value.
The isNaN()
method checks if the passed value is a number.
The Number.isInteger()
method is used to check if the number is an integer value.
Example 2: Using Regex
// program to check if a number is a float or integer value
function checkNumber(x) {
let regexPattern = /^-?[0-9]+$/;
// check if the passed number is integer or float
let result = regexPattern.test(x);
if(result) {
console.log(`${x} is an integer.`);
}
else {
console.log(`${x} is a float value.`)
}
}
checkNumber(44);
checkNumber(-44);
checkNumber(3.4);
checkNumber(-3.4);
Output
44 is an integer.
-44 is an integer.
3.4 is a float value.
-3.4 is a float value.
In the above example, the regex pattern is used to check if the passed argument is an integer value or float value.
The pattern /^-?[0-9]+$/
looks for the integer value.
The test()
method of the RegExp
object is used to test the pattern with the given value.
Note: The above program only works for numbers.
Pass a Function as Parameter
In this example, you will learn to write a JavaScript program that will pass a function as a parameter.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Function and Function Expressions
Example: Function as Parameter
// program to pass a function as a parameter
function greet() {
return 'Hello';
}
// passing function greet() as a parameter
function name(user, func)
{
// accessing passed function
const message = func();
console.log(`${message} ${user}`);
}
name('John', greet);
name('Jack', greet);
name('Sara', greet);
Output
Hello John
Hello Jack
Hello Sara
In the above program, there are two functions: name()
and greet()
.
The name()
function takes two parameters.
The greet()
function is passed as an argument to the name()
function.
Get the Dimensions of an Image
In this example, you will learn to write a JavaScript program that will get the dimensions of an image.
Example: Get Dimensions of an Image
// program to get the dimensions of an image
const img = new Image();
// get the image
img.src = '//cdn.programiz.com/sites/tutorial2program/files/cover-artwork.png';
// get height and width
img.onload = function() {
console.log('width ' + this.width)
console.log('height '+ this.height);
}
Output
width 1040
height 922
In the above program, new Image()
constructor is used to create an image object.
The Image()
constructor creates a new image element instance.
img.src
is then used to add the image using an image URL source.
The img.onload()
function is used to access the height and width of the image.
Remove All Whitespaces From a Text
In this example, you will learn to write a JavaScript program that will remove all whitespaces from a text.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript String split()
Javascript Array join()
JavaScript Regex
Example 1: Using split() and join()
// program to trim a string
const string = ' Hello World ';
const result = string.split(' ').join('');
console.log(result);
Output
HelloWorld
In the above program,
The split(' ')
method is used to split the strings into individual array elements.
["", "", "", "", "", "", "Hello", "World", "", "", "", "", "", "", ""]
The join('')
method merges the array into a string.
Example 2: Using Regular Expression
// program to trim a string
function trimString(x) {
const result = x.replace(/\s/g,'');
return result
}
const result = trimString(' Hello World ');
console.log(result);
Output
HelloWorld
In the above program, the Regular Expression is used with the replace()
method to remove all whitespaces from a text.
/\s/g
checks for whitespace in the string.
Write to Console
In this example, you will learn to write a JavaScript program that will allow you to write to the console.
Example: Using console.log()
// program to write to console
// passing number
console.log(8);
// passing string
console.log('hello');
// passing variable
const x = 'hello';
console.log(x);
// passing function
function sayName() {
return 'Hello John';
}
console.log(sayName());
// passing string and a variable
const name = 'John';
console.log('Hello ' + name);
// passing object
let obj = {
name: 'John',
age: 28
}
console.log(obj);
Output
8
hello
hello
Hello John
Hello John
{
age: 28,
name: "John"
}
The console.log()
method is used to write to the console.
You can pass values directly into the method or pass a variable to write to a console.
Convert Date to Number
In this example, you will learn to write a JavaScript program that will convert a date to a number.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
JavaScript Date and Time
Example: Convert Date to Number
// program to convert date to number
// create date
const d1 = new Date();
console.log(d1);
// converting to number
const result = d1.getTime();
console.log(result);
Output
Mon Nov 09 2020 10:52:32 GMT+0545 (Nepal Time)
1604898452084
In the above example, the new Date()
constructor is used to create a date object.
The new Date()
gives the current date and time.
const d1 = new Date();
console.log(d1); // Mon Nov 09 2020 10:52:32 GMT+0545 (Nepal Time)
To convert the name to a number, we use the getTime()
method.
The getTime()
method returns the number of milliseconds from midnight of January 1, 1970 (EcmaScript epoch) to the specified date.
const d1 = new Date().getTime();
console.log(d1); // 1604898452084
Argument
The arguments object is an array-like object (in that the structure of the object is similar to that of an array; however it should not be considered an array as it has all the functionality of an object) that stores all of the arguments that you passed to a function and is proprietary to that function in particular.
If you were to pass 3 arguments to a function, say storeNames()
, those 3 arguments would be stored inside an object called arguments and it would look like this when we pass the arguments storeNames("Mulder", "Scully", "Alex Krycek")
to our function:
First, we declare a function and make it return the arguments object.
Then, when we execute that function with n arguments, 3 in this case, it will return the object to us and it will look like an array.
We can convert it to an array, but more on that later…
function storeNames() { return arguments; }
// If we execute the following line in the console:
storeNames("Mulder", "Scully", "Alex Kryceck");
// The output will be { '0': 'Mulder', '1': 'Scully', '2': 'Alex Kryceck' }
Treat it as an array
You can invoke arguments by using arguments[n]
(where n is the index of the argument in the array-like object).
But if you want to use it as an array for iteration purposes or applying array methods to it, you need to convert it to an array by declaring a variable and using the Array.prototype.slice.call method (because arguments is not an array):
var args = Array.prototype.slice.call(arguments);
// or the es6 way:
var args = Array.from(arguments)
Since slice() has two (the parameter end is optional) parameters.
You can grab a certain portion of the arguments by specifying the beginning and the ending of your portion (using the slice.call() method renders these two parameters optional, not just end).
Check out the following code:
function getGrades() {
var args = Array.prototype.slice.call(arguments, 1, 3);
return args;
}
// Let's output this!
console.log(getGrades(90, 100, 75, 40, 89, 95));
// OUTPUT SHOULD BE: //
// [100, 75] <- Why? Because it started from index 1 and stopped at index 3
// so, index 3 (40) wasn't taken into consideration.
//
// If we remove the '3' parameter, leaving just (arguments, 1) we'd get
// every argument from index 1: [100, 75, 40, 89, 95].
Optimization issues with Array.slice()
There is a little problem: it’s not recommended to use slice in the arguments object (optimization reasons)…
Important: You should not slice on arguments because it prevents optimizations in JavaScript engines (V8 for example).
Instead, try constructing a new array by iterating through the arguments object.
So, what other method is available to convert arguments to an array? I recommend the for-loop (not the for-in loop).
You can do it like this:
var args = []; // Empty array, at first.
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i])
} // Now 'args' is an array that holds your arguments.
For more information on the optimization issues:
Optimization Killers: Managing Arguments
ES6 rest parameter as a way to circumvent the arguments object
In ES2015/ES6 it is possible to use the rest parameter (...
) instead of the arguments object in most places.
Say we have the following function (non-ES6):
function getIntoAnArgument() {
var args = arguments.slice();
args.forEach(function(arg) {
console.log(arg);
});
}
That function can be replaced in ES6 by:
function getIntoAnArgument(...args) {
args.forEach(arg => console.log(arg));
}
Note that we also used an arrow function to shorten the forEach callback!
The arguments object is not available inside the body of an arrow function.
The rest parameter must always come as the last argument in your function definition.
function getIntoAnArgument(arg1, arg2, arg3, ...restOfArgs /*no more arguments allowed here*/) { //function body }
Arithmetic Operation
JavaScript provides the user with five arithmetic operators: +
, -
, *
, /
and %
.
The operators are for addition, subtraction, multiplication, division and remainder, respectively.
Addition
Syntax
a + b
Usage
2 + 3 // returns 5
true + 2 // interprets true as 1 and returns 3
false + 5 // interprets false as 0 and returns 5
true + "bar" // concatenates the boolean value and returns "truebar"
5 + "foo" // concatenates the string and the number and returns "5foo"
"foo" + "bar" // concatenates the strings and returns "foobar"
Hint: There is a handy increment operator that is a great shortcut when you’re adding numbers by 1.
Subtraction
Syntax
a - b
Usage
2 - 3 // returns -1
3 - 2 // returns 1
false - 5 // interprets false as 0 and returns -5
true + 3 // interprets true as 1 and returns 4
5 + "foo" // returns NaN (Not a Number)
Hint: There is a handy decrement operator that is a great shortcut when you’re subtracting numbers by 1.
Multiplication
Syntax
a * b
Usage
2 * 3 // returns 6
3 * -2 // returns -6
false * 5 // interprets false as 0 and returns 0
true * 3 // interprets true as 1 and returns 3
5 * "foo" // returns NaN (Not a Number)
Infinity * 0 // returns NaN
Infinity * Infinity // returns Infinity
Hint: When making calculations it is possible to use parentheses to prioritize which numbers should be multiplied together.
Division
Syntax
a / b
Usage
3 / 2 // returns 1.5
3.0 / 2/0 // returns 1.5
3 / 0 // returns Infinity
3.0 / 0.0 // returns Infinity
-3 / 0 // returns -Infinity
false / 5 // interprets false as 0 and returns 0
true / 2 // interprets true a 1 and returns 0.5
5 + "foo" // returns NaN (Not a Number)
Infinity / Infinity // returns NaN
Remainder
Syntax
a % b
Usage
3 % 2 // returns 1
true % 5 // interprets true as 1 and returns 1
false % 4 // interprets false as 0 and returns 0
3 % "bar" // returns NaN
Increment
Syntax
a++ or ++a
Usage
// Postfix
x = 3; // declare a variable
y = x++; // y = 4, x = 3
// Prefix
var a = 2;
b = ++a; // a = 3, b = 3
Decrement
Syntax
a-- or --a
Usage
// Postfix
x = 3; // declare a variable
y = x—; // y = 3, x = 3
// Prefix
var a = 2;
b = —a; // a = 1, b = 1
Important: As you can see, you cannot perform any sort of operations on Infinity
.
Arrow Function Example
Arrow functions are a new ES6 syntax for writing JavaScript function expressions.
The shorter syntax saves time, as well as simplifying the function scope.
What are arrow functions?
An arrow function expression is a more concise syntax for writing function expressions using a “fat arrow” token (=>
).
The basic syntax
Below is a basic example of an arrow function:
// ES5 syntax
var multiply = function(x, y) {
return x * y;
};
// ES6 arrow function
var multiply = (x, y) => { return x * y; };
// Or even simpler
var multiply = (x, y) => x * y;
You no longer need the function
and return
keywords, or even the curly brackets.
A simplified this
Before arrow functions, new functions defined their own this
value.
To use this
inside a traditional function expression, we have to write a workaround like so:
// ES5 syntax
function Person() {
// we assign `this` to `self` so we can use it later
var self = this;
self.age = 0;
setInterval(function growUp() {
// `self` refers to the expected object
self.age++;
}, 1000);
}
An arrow function doesn’t define its own this
value, it inherits this
from the enclosing function:
// ES6 syntax
function Person(){
this.age = 0;
setInterval(() => {
// `this` now refers to the Person object, brilliant!
this.age++;
}, 1000);
}
var p = new Person();
Assignment Operators
Assignment Operator
Assignment operators, as the name suggests, assign (or re-assign) values to a variable.
While there are quite a few variations on the assignment operators, they all build off of the basic assignment operator.
Syntax = y;DescriptionNecessityxVariableRequired=Assignment operatorRequiredyValue to assign to variableRequired
Examples
let initialVar = 5; // Variable initialization requires the use of an assignment ope
rator
let newVar = 5;
newVar = 6; // Variable values can be modified using an assignment operator
Variations
The other assignment operators are a shorthand for performing some operation using the variable (indicated by x above) and value (indicated by y above) and then assigning the result to the variable itself.
For example, below is the syntax for the addition assignment operator:
x += y;
This is the same as applying the addition operator and reassigning the sum to the original variable (that is, x), which can be expressed by the following code:
x = x + y;
To illustrate this using actual values, here is another example of using the addition assignment operator:
let myVar = 5; // value of myVar: 5
myVar += 7; // value of myVar: 12 = 5 + 7
Complete list of JavaScript’s assignment operators
Operator |
Syntax |
Long version |
Assignment |
x = y |
x = y |
Addition assignment |
x += y |
x = x + y |
Subtraction assignment |
x -= y |
x = x - y |
Multiplication assignment |
x *= y |
x = x * y |
Division assignment |
x /= y |
x = x / y |
Remainder assignment |
x %= y |
x = x % y |
Exponentiation assignment |
x **= y |
x = x ** y |
Left shift assignment |
x <<= y |
x = x << y |
Right shift assignment |
x >>= y |
x = x >> y |
Unsigned right shift assignment |
x >>>= y |
x = x >>> y |
Bitwise AND assignment |
x &= y |
x = x & y |
Bitwise XOR assignment |
x ^= y |
x = x ^ y |
Bitwise OR assignment |
x |= y |
x = x | y |
Boolean Example
Booleans are a primitive datatype commonly used in computer programming languages.
By definition, a boolean has two possible values: true
or false
.
In JavaScript, there is often implicit type coercion to boolean.
If for example you have an if statement which checks a certain expression, that expression will be coerced to a boolean:
var a = 'a string';
if (a) {
console.log(a); // logs 'a string'
}
There are only a few values that will be coerced to false:
false (not really coerced, as it already is false)
null
undefined
NaN
0
” (empty string)
All other values will be coerced to true.
When a value is coerced to a boolean, we also call that either ‘falsy’ or ‘truthy’.
One way that type coercion is used is with the use of the or (||
) and and (&&
) operators:
var a = 'word';
var b = false;
var c = true;
var d = 0
var e = 1
var f = 2
var g = null
console.log(a || b); // 'word'
console.log(c || a); // true
console.log(b || a); // 'word'
console.log(e || f); // 1
console.log(f || e); // 2
console.log(d || g); // null
console.log(g || d); // 0
console.log(a && c); // true
console.log(c && a); // 'word'
As you can see, the or operator checks the first operand.
If this is true or truthy, it returns it immediately (which is why we get ‘word’ in the first case & true in the second case).
If it is not true or truthy, it returns the second operand (which is why we get ‘word’ in the third case).
With the and operator it works in a similar way, but for ‘and’ to be true, both operands need to be truthy.
So it will always return the second operand if both are true/truthy, otherwise it will return false.
That is why in the fourth case we get true and in the last case we get ‘word’.
The Boolean Object
There is also a native JavaScript Boolean
object that wraps around a value and converts the first parameter to a boolean value.
If a value is omitted or falsy –0, -0, null
, false
, NaN
, undefined
, or an empty string (""
) – the object's value is false.
Pass all other values, including the string "false"
, and the object's value is set to true.
Note that primitive Boolean values (true
and false
) are different than those of the Boolean object.
More Details
Remember that any object, the value of which is not undefined
or null
, evaluates to true if used in a conditional statement.
For example, even though this Boolean
object is explicitly set to false, it evaluates to true and the code is executed:
var greeting = new Boolean(false);
if (greeting) {
console.log("Hello world");
}
// Hello world
This doesn't apply to boolean primitives:
var greeting = false;
if (greeting) {
console.log("Hello world"); // code will not run
}
To convert a non-boolean value to a boolean, use Boolean
as a function rather than as an object:
var x = Boolean(expression); // preferred use as a function
var x = new Boolean(expression); // don't do it this way
Callback Functions
This section gives a brief introduction to the concept and usage of callback functions in JavaScript.
Functions are Objects
The first thing we need to know is that in JavaScript, functions are first-class objects.
As such, we can work with them in the same way we work with other objects, like assigning them to variables and passing them as arguments into other functions.
This is important, because it’s the latter technique that allows us to extend functionality in our applications.
Callback Function Example
A callback function is a function that is passed as an argument to another function, to be “called back” at a later time.
A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.
It’s the combination of these two that allow us to extend our functionality.
To illustrate callbacks, let’s start with a simple example:
function createQuote(quote, callback){
var myQuote = "Like I always say, " + quote;
callback(myQuote); // 2
}
function logQuote(quote){
console.log(quote);
}
createQuote("eat your vegetables!", logQuote); // 1
// Result in console:
// Like I always say, eat your vegetables!
In the above example, createQuote
is the higher-order function, which accepts two arguments, the second one being the callback.
The logQuote
function is being used to pass in as our callback function.
When we execute the createQuote
function (1), notice that we are not appending parentheses to logQuote
when we pass it in as an argument.
This is because we do not want to execute our callback function right away, we simply want to pass the function definition along to the higher-order function so that it can be executed later.
Also, we need to ensure that if the callback function we pass in expects arguments, we supply those arguments when executing the callback (2).
In the above example, that would be the callback(myQuote);
statement, since we know that logQuote
expects a quote to be passed in.
Additionally, we can pass in anonymous functions as callbacks.
The below call to createQuote
would have the same result as the above example:
createQuote("eat your vegetables!", function(quote){
console.log(quote);
});
Incidentally, you don’t have to use the word “callback” as the name of your argument.
JavaScript just needs to know that it’s the correct argument name.
Based on the above example, the below function will behave in exactly the same manner.
function createQuote(quote, functionToCall) {
var myQuote = "Like I always say, " + quote;
functionToCall(myQuote);
}
Why use Callbacks?
Most of the time we are creating programs and applications that operate in a synchronous manner.
In other words, some of our operations are started only after the preceding ones have completed.
Often when we request data from other sources, such as an external API, we don’t always know when our data will be served back.
In these instances we want to wait for the response, but we don’t always want our entire application grinding to a halt while our data is being fetched.
These situations are where callback functions come in handy.
Let’s take a look at an example that simulates a request to a server:
function serverRequest(query, callback){
setTimeout(function(){
var response = query + "full!";
callback(response);
},5000);
}
function getResults(results){
console.log("Response from the server: " + results);
}
serverRequest("The glass is half ", getResults);
// Result in console after 5 second delay:
// Response from the server: The glass is half full!
In the above example, we make a mock request to a server.
After 5 seconds elapse, the response is modified and then our callback function getResults
gets executed.
To see this in action, you can copy/paste the above code into your browser’s developer tool and execute it.
Also, if you are already familiar with setTimeout
, then you’ve been using callback functions all along.
The anonymous function argument passed into the above example’s setTimeout
function call is also a callback! So the example’s original callback is actually executed by another callback.
Be careful not to nest too many callbacks if you can help it, as this can lead to something called “callback hell”! As the name implies, it isn’t a joy to deal with.
JavaScript Class Example
JavaScript does not have the concept of classes inherently.
But we could simulate the functionalities of a class by taking advantage of the prototypal nature of JavaScript.
This section assumes that you have a basic understanding of prototypes.
For the sake of clarity, let us assume that we want to create a class which can do the following
var p = new Person('James','Bond'); // create a new instance of Person class
p.log() // Output: 'I am James Bond' // Accessing a function in the class
// Using setters and getters
p.profession = 'spy'
p.profession // output: James bond is a spy
Using class keyword
Like in any other programming language, you can now use the class
keyword to create a class.
This is not supported in older browsers and was introduced in ECMAScript 2015.
class
is just a syntactic sugar over JavaScript’s existing prototype-based inheritance model.
In general, programmers use the following ways to create a class in JavaScript.
Using methods added to prototypes:
Here, all the methods are added to prototype
function Person(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
Person.prototype.log = function() {
console.log('I am', this._firstName, this._lastName);
}
// This line adds getters and setters for the profession object.
Note that in general you could just write your own get and set functions like the 'log' method above.
// Since in this example we are trying the mimic the class above, we try to use the getters and setters property provided by JavaScript
Object.defineProperty(Person.prototype, 'profession', {
set: function(val) {
this._profession = val;
},
get: function() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
})
You could also write prototype methods over function Person
as below:
Person.prototype = {
log: function() {
console.log('I am ', this._firstName, this._lastName);
}
set profession(val) {
this._profession = val;
}
get profession() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
}
Using methods added internally
Here the methods are added internally instead of prototype:
function Person(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
this.log = function() {
console.log('I am ', this._firstName, this._lastName);
}
Object.defineProperty(this, 'profession', {
set: function(val) {
this._profession = val;
},
get: function() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
})
}
Hiding details in classes with symbols
Most often, some properties and methods have to be hidden to prevent access from outside the function.
With classes, to obtain this functionality, one way to do this is by using symbols.
Symbol is a new built-in type of JavaScript, which can be invoked to give a new symbol value.
Every Symbol is unique and can be used as a key on object.
So one use case of symbols is that you can add something to an object you might not own, and you might not want to collide with any other keys of object.
Therefore, creating a new one and adding it as a property to that object using symbol is the safest.
Also, when symbol value is added to an object, no one else will know how to get it.
class Person {
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
log() {
console.log('I am', this._firstName, this._lastName);
}
// setters
set profession(val) {
this._profession = val;
}
// getters
get profession() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
// With the above code, even though we can access the properties outside the function to change their content what if we don't want that.
// Symbols come to rescue.
let s_firstname = new Symbol();
class Person {
constructor(firstName, lastName) {
this[s_firstName] = firstName;
this._lastName = lastName;
}
log() {
console.log('I am', this._firstName, this._lastName);
}
// setters
set profession(val) {
this._profession = val;
}
// getters
get profession() {
console.log(this[s_firstName], this._lastName, 'is a', this._profession);
}
JavaScript Closure Example
A closure is the combination of a function and the lexical environment (scope) within which that function was declared.
Closures are a fundamental and powerful property of Javascript.
This section discusses the ‘how’ and ‘why’ about Closures:
Example
//we have an outer function named walk and an inner function named fly
function walk (){
var dist = '1780 feet';
function fly(){
console.log('At '+dist);
}
return fly;
}
var flyFunc = walk(); //calling walk returns the fly function which is being assigned to flyFunc
//you would expect that once the walk function above is run
//you would think that JavaScript has gotten rid of the 'dist' var
flyFunc(); //Logs out 'At 1780 feet'
//but you still can use the function as above
//this is the power of closures
Another Example
function by(propName) {
return function(a, b) {
return a[propName] - b[propName];
}
}
const person1 = {name: 'joe', height: 72};
const person2 = {name: 'rob', height: 70};
const person3 = {name: 'nicholas', height: 66};
const arr_ = [person1, person2, person3];
const arr_sorted = arr_.sort(by('height')); // [ { name: 'nicholas', height: 66 }, { name: 'rob', height: 70 },{ name: 'joe', height: 72 } ]
The closure ‘remembers’ the environment in which it was created.
This environment consists of any local variables that were in-scope at the time the closure was created.
function outside(num) {
var rememberedVar = num; // In this example, rememberedVar is the lexical environment that the closure 'remembers'
return function inside() { // This is the function which the closure 'remembers'
console.log(rememberedVar)
}
}
var remember1 = outside(7); // remember1 is now a closure which contains rememberedVar = 7 in its lexical environment, and //the function 'inside'
var remember2 = outside(9); // remember2 is now a closure which contains rememberedVar = 9 in its lexical environment, and //the function 'inside'
remember1(); // This now executes the function 'inside' which console.logs(rememberedVar) => 7
remember2(); // This now executes the function 'inside' which console.logs(rememberedVar) => 9
Closures are useful because they let you ‘remember’ data and then let you operate on that data through returned functions.
This allows Javascript to emulate private methods that are found in other programming languages.
Private methods are useful for restricting access to code as well as managing your global namespace.
Private variables and methods
Closures can also be used to encapsulate private data/methods.
Take a look at this example:
const bankAccount = (initialBalance) => {
const balance = initialBalance;
return {
getBalance: function() {
return balance;
},
deposit: function(amount) {
balance += amount;
return balance;
},
};
};
const account = bankAccount(100);
account.getBalance(); // 100
account.deposit(10); // 110
In this example, we won’t be able to access balance
from anywhere outside of the bankAccount
function, which means we’ve just created a private variable.
Where’s the closure? Well, think about what bankAccount()
is returning.
It actually returns an Object with a bunch of functions inside it, and yet when we call account.getBalance()
, the function is able to “remember” its initial reference to balance
.
That is the power of the closure, where a function “remembers” its lexical scope (compile time scope), even when the function is executed outside that lexical scope.
Emulating block-scoped variables
Javascript did not have a concept of block-scoped variables.
Meaning that when defining a variable inside a for-loop, for example, this variable was visible from outside the for-loop as well.
So how can closures help us solve this problem? Let’s take a look.
var funcs = [];
for(var i = 0; i < 3; i++){
funcs[i] = function(){
console.log('My value is ' + i); //creating three different functions with different param values.
}
}
for(var j = 0; j < 3; j++){
funcs[j](); // My value is 3
// My value is 3
// My value is 3
}
Since the variable i does not have block-scope, it’s value within all three functions was updated with the loop counter and created malicious values.
Closures can help us solve this issue by creating a snapshot of the environment the function was in when it was created, preserving its state.
var funcs = [];
var createFunction = function(val){
return function() {console.log("My value: " + val);};
}
for (var i = 0; i < 3; i++) {
funcs[i] = createFunction(i);
}
for (var j = 0; j < 3; j++) {
funcs[j](); // My value is 0
// My value is 1
// My value is 2
}
The later versions of Javascript (ES6+) have a new keyword called let which can be used to give the variable a blockscope.
There are also many functions (forEach) and entire libraries (lodash.js) that are dedicated to solving such problems as the ones explained above.
They can certainly boost your productivity, however it remains extremely important to have knowledge of all these issues when attempting to create something big.
Closures have many special applications that are useful when creating large Javascript programs.
Emulating private variables or encapsulation
Making Asynchronous server side calls
Creating a block-scoped variable.Emulating private variables
Unlike many other languages, Javascript does not have a mechanism which allows you to create encapsulated instance variables within an object.
Having public instance variables can cause a lot of problems when building medium to large programs.
However with closures, this problem can be mitigated.
Much like in the previous example, you can build functions which return object literals with methods that have access to the object’s local variables without exposing them.
Thus, making them effectively private.
Closures can also help you manage your global namespace to avoid collisions with globally shared data.
Usually, all global variables are shared between all scripts in your project, which will definitely give you a lot of trouble when building medium to large programs.
That is why library and module authors use closures to hide an entire module’s methods and data.
This is called the module pattern, it uses an immediately invoked function expression which exports only certain functionality to the outside world, significantly reducing the amount of global references.
Here’s a short sample of a module skeleton.
var myModule = (function() = {
let privateVariable = 'I am a private variable';
let method1 = function(){ console.log('I am method 1'); };
let method2 = function(){ console.log('I am method 2, ', privateVariable); };
return {
method1: method1,
method2: method2
}
}());
myModule.method1(); // I am method 1
myModule.method2(); // I am method 2, I am a private variable
Closures are useful for capturing new instances of private variables contained in the ‘remembered’ environment, and those variables can only be accessed through the returned function or methods.
JavaScript Comment Example
Programmers use comments to add hints, notes, suggestions, or warnings to their source code; they have no effect on the actual output of the code.
Comments can be very helpful in explaining the intent of what your code is or should be doing.
It is always best practice when starting out to comment more often than not, as it can help those reading your code to understand what exactly your code is intending to do.
JavaScript has two ways of assigning comments in its code.
The first way is the //
comment; all text following //
on the same line into a comment.
For example:
function hello() {
// This is a one line JavaScript comment
console.log("Hello world!");
}
hello();
The second way is the /* */
comment, which can be used for both single-line and multi-line comments.
For example:
function hello() {
/* This is a one line JavaScript comment */
console.log("Hello world!");
}
hello();
function hello() {
/* This comment spans multiple lines.
Notice
that we don't need to end the comment until we're done.
*/
console.log("Hello world!");
}
hello();
You can also prevent execution of Javascript code just commeting the code lines like this:
function hello() {
/*console.log("Hello world!");*/
}
hello();
More Information:
How To Write Comments in JavaScript
Many IDEs come with a keyboard shortcut to comment out lines.
Highlight text to be commented
Mac: Push Command(Apple Key) & "/"
Windows: Push Control & "/"
You can also uncomment code by doing the same steps
A shortcut to comment out a section of Javascript in many code editors is to highlight the lines of code you want to comment out, then press `Cmd/Ctrl + /`.
Comments are also very helpful for code testing as you can prevent a certain code-line/block from running:
function hello() {
// The statement below is not going to get executed
// console.log('hi')
}
hello();
function hello() {
// The statements below are not going to get executed
/*
console.log('hi');
console.log('code-test');
*/
}
hello();
Comparison Operator
JavaScript has both strict and type–converting comparisons.
The strict comparison (===
) only evaluates to true if both operands are the same type.
The abstract comparison (==
) attempts to convert both operands to the same type before comparing them.
With relational abstract comparisons (<=
), both operands are converted to primitives, then to the same type before comparison.
Strings are compared using Unicode values based on standard ordering.
Features of comparisons:
Two strings are considered strictly equal when they have the characters in the same sequence and the same length.
Two numbers are considered strictly equal when they are the both of the type number and are numerically equal.
This means that both 0
and -0
are strictly equal since they both evaluate to 0
.
Note that NaN
is a special value and is not equal to anything, including NaN
.
Two Boolean operands are considered strictly equal if both are true
or false
.
Two objects are never considered equal in both strict or abstract comparisons.
Expressions that compare objects are only considered true if the operands both reference the same exact object instance.
Null and undefined are both considered strictly equal to themselves (null === null
) and abstractly equal to each other (null == undefined
)
Equality operators
Equality (==)
The equality operator first converts operands that are not of the same type, then strictly compares them to one another.
Syntax
x == y
Examples
1 == 1 // true
"1" == 1 // true
1 == '1' // true
0 == false // true
0 == null // false
0 == undefined // false
null == undefined // true
Inequality (!=)
The inequality operator evaluates to true if both operands are not equal.
If the operands are not the same type, it will try to convert them to the same type before making the comparison.
Syntax
x != y
Examples
1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false
Identity / strict equality (===)
The identity or strict equality operator returns true if both operands are strictly equal in terms of value and type.
Unlike the equality operator (==
), it will not attempt to convert the operands to the same type.
Syntax
x === y
Examples
3 === 3 // true
3 === '3' // false
Non-identity / strict inequality (!==)
The non-identity or strict inequality operator returns true if both operands are not strictly equal in terms of value or type.
Syntax
x !== y
Examples
3 !== '3' // true
4 !== 3 // true
Relational operators
Greater than operator (>)
The greater than operator returns true if the operand on the left is greater than the one on the right.
Syntax
x > y
Examples
4 > 3 // true
Greater than or equal operator (>=)
The greater than or equal operator returns true if the operand on the left is greater than or equal to the one on the right.
Syntax
x >= y
Examples
4 >= 3 // true
3 >= 3 // true
Less than operator (<)
The less than operator returns true if the operand on the left is less than the one on the right.
Syntax
x < y
Examples
3 < 4 // true
Less than or equal operator (<=)
The less than or equal operator returns true if the operand on the left is less than or equal to the one on the right.
Syntax
x <= y
Examples
3 <= 4 // true
JavaScript Form Validation Example
Form validation used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button.
If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information.
This was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form’s data on the client’s computer before sending it to the web server.
Form validation generally performs two functions:
Basic Validation
First of all, the form must be checked to make sure all the mandatory fields are filled in.
It just requires a loop through each field in the form to check for data.
Data Format Validation
Secondly, the data that is entered must be checked for correct form and value.
Your code must include appropriate logic to test the correctness of the data.
Example:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Output
Have a look here.
Basic Form Validation
First let us see how to do a basic form validation.
In the above form, we are calling validate() to validate data when the onsubmit event is occurring.
The following code shows the implementation of this validate()
function.
<script type="text/javascript">
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
</script>
Output
Have a look here.
Data Format Validation
Now we will see how we can validate our entered form data before submitting it to the web server.
The following example shows how to validate an entered email address.
An email address must contain at least an ‘@’ sign and a dot (.).
Also, the ‘@’ must not be the first character of the email address, and the last dot must at least be one character after the ‘@’ sign.
Example:
<script type="text/javascript">
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
</script>
Output
Have a look here.
HTML5 Form Constraints
Some of the commonly used HTML5 constraints for <input>
are the type
attribute (e.g.
type="password"
), maxlength
, required
and disabled
.
A less commonly used constraint is the pattern
attribute that takes a JavaScript regular expression.
If statement
The if
statement executes a statement if a specified condition is true
.
If the condition is false
, another statement can be executed using the else
statement.
Note: The else
statement is optional.
if (condition)
/* do something */
else
/* do something else */
Multiple if...else
statements can be chained to create an else if
clause.
This specifies a new condition to test and can be repeated to test multiple conditions, checking until a true statement is presented to execute.
if (condition1)
/* do something */
else if (condition2)
/* do something else */
else if (condition3)
/* do something else */
else
/* final statement */
Note: If you want to execute more than one statement in the if
, else
or else if
part, curly braces are required around the statements:
if (condition) {
/* do */
/* something */
/* with multiple statements */
} else {
/* do something */
/* else */
}
MDN link | MSDN link
Examples
Using if...else
:
// If x=5 z=7 and q=42.
If x is not 5 then z=19.
if (x == 5) {
z = 7;
q = 42
else
z = 19;
Using else if
:
if (x < 10)
return "Small number";
else if (x < 50)
return "Medium number";
else if (x < 100)
return "Large number";
else {
flag = 1;
return "Invalid number";
}
Prototype
JavaScript is a prototype-based language, therefore understanding the prototype object is one of the most important concepts which JavaScript practitioners need to know.
This section will give you a short overview of the Prototype object through various examples.
Before reading this part, you will need to have a basic understanding of the this
reference in JavaScript.
Prototype object
For the sake of clarity, let’s examine the following example:
function Point2D(x, y) {
this.x = x;
this.y = y;
}
As Point2D
function is declared, a default property named prototype
will be created for it (note that, in JavaScript, a function is also an object).
The prototype
property is an object which contains a constructor
property and its value is Point2D
function: Point2D.prototype.constructor = Point2D
.
And when you call Point2D
with new
keyword, newly created objects will inherit all properties from Point2D.prototype
.
To check that, you can add a method named move
into Point2D.prototype
as follows:
Point2D.prototype.move = function(dx, dy) {
this.x += dx;
this.y += dy;
}
var p1 = new Point2D(1, 2);
p1.move(3, 4);
console.log(p1.x); // 4
console.log(p1.y); // 6
The Point2D.prototype
is called prototype object or prototype of p1
object and for any other object created with new Point2D(...)
syntax.
You can add more properties to Point2D.prototype
object as you like.
The common pattern is to declare methods to Point2D.prototype
and other properties will be declared in the constructor function.
Built-in objects in JavaScript are constructed in a similar manner.
For example:
Prototype of objects created with new Object()
or {}
syntax is Object.prototype
.
Prototype of arrays created with new Array()
or []
syntax is Array.prototype
.
And so on with other built-in objects such as Date
and RegExp
.
Object.prototype
is inherited by all objects and it has no prototype (its prototype is null
).
Prototype chain
The prototype chain mechanism is simple: When you access a property p
on object obj
, the JavaScript engine will search this property inside obj
object.
If the engine fails to search, it continues searching in the prototype of obj
object and so on until reaching Object.prototype
.
If after the search has finished, and nothing has been found, the result will be undefined
.
For example:
var obj1 = {
a: 1,
b: 2
};
var obj2 = Object.create(obj1);
obj2.a = 2;
console.log(obj2.a); // 2
console.log(obj2.b); // 2
console.log(obj2.c); // undefined
In above snippet, the statement var obj2 = Object.create(obj1)
will create obj2
object with prototype obj1
object.
In other words, obj1
becomes the prototype of obj2
instead of Object.prototype
by default.
As you can see, b
is not a property of obj2
; you can still access it via the prototype chain.
For the c
property, however, you get an undefined
value because it can’t be found in obj1
and Object.prototype
.
Classes
In ES2016, we now get to use the Class
keyword as well as the methods mentioned above to manipulate prototype
.
The JavaScript Class
appeals to developers from OOP backgrounds, but it’s essentially doing the same thing as above.
class Rectangle {
constructor(height, width) {
this.height = height
this.width = width
}
get area() {
return this.calcArea()
}
calcArea() {
return this.height * this.width
}
}
const square = new Rectangle(10, 10)
console.log(square.area) // 100
This is basically the same as:
function Rectangle(height, width) {
this.height = height
this.width = width
}
Rectangle.prototype.calcArea = function calcArea() {
return this.height * this.width
}
The getter
and setter
methods in classes bind an Object property to a function that will be called when that property is looked up.
It’s just syntactic sugar to help make it easier to look up or set properties.
Scope
If you’ve been programming in JavaScript for a while, you’ve undoubtedly run into a concept known as scope
.
What is scope
? Why should you take the time to learn it?
In programmer speak, scope
is the current context of execution.
Confused? Let’s take a look at the following piece of code:
var foo = 'Hi, I am foo!';
var baz = function () {
var bar = 'Hi, I am bar too!';
console.log(foo);
}
baz(); // Hi, I am foo!
console.log(bar); // ReferenceError...
This is a simple example, but it does a good job of illustrating what is known as Lexical scope.
JavaScript, and almost every other programming language, has a Lexical scope.
There is another kind of scope known as Dynamic scope, but we won’t be discussing that.
Now, the term Lexical scope sounds fancy, but as you will see it’s really simple in principle.
In a Lexical Scope, there are two kinds of scopes: the global scope and a local scope.
Before you type the first line of code in your program, a global scope is created for you.
This contains all the variables that you declare in your program outside any functions.
In the example above, the variable foo
is in the global scope of the program, while the variable bar
is declared inside a function and is therefore in the local scope of that function.
Let's break down the example line by line.
While you might be confused at this point, I promise you will have a much better understanding by the time you finish reading this.
On line 1 we are declaring the variable foo
.
Nothing too fancy here.
Let's call this a left-hand size (LHS) reference to foo
, because we are assigning a value to foo
and it’s on the left-hand side of the equal
sign.
On line 3, we are declaring a function and assigning it to variable baz
.
This is another LHS reference to baz
.
We are assigning a value to it (remember, functions are values too!).
This function is then called on line 8.
This is a RHS, or a right-hand side reference to baz
.
We are retrieving baz
’s value, which in this case is a function and then invoking it.
Another RHS reference to baz
would be if we assigned its value to another variable, for example foo = baz
.
This would be a LHS reference to foo
and a RHS reference to baz
.
The LHS and RHS references might sound confusing, but they are important for discussing scope.
Think of it this way: a LHS reference is assigning a value to the variable, while a RHS reference is retrieving the value of the variable.
They’re just a shorter and more convenient way of saying ‘retrieving the value’ and ‘assigning a value’.
Let’s now break down what’s happening inside the function itself.
When the compiler compiles the code inside a function, it enters the function’s local scope.
On line 4, the variable bar
is declared.
This is a LHS reference to bar
.
On the next line, we have a RHS reference to foo
inside the console.log()
.
Remember, we are retrieving foo
’s value and then passing it as an argument to the method console.log()
.
When we have a RHS reference to foo
, the compiler looks for the declaration of the variable foo
.
The compiler doesn’t find it in the function itself, or the function’s local scope, so it goes up one level: to the global scope.
At this point you’re probably thinking that scope has something to do with variables.
That is correct.
A scope can be thought of as a container for variables.
All variables that are created within a local scope are only accessible in that local scope.
However, all local scopes can access the global scope.
(I know you’re probably even more confused right now, but just bear with me for a few more paragraphs).
So the compiler goes up to the global scope to find a LHS reference to the variable foo
.
It finds one on line 1, so it retrieves the value from the LHS reference, which is a string: 'Hi, I am foo!'
.
This string is sent to the console.log()
method, and outputted to the console.
The compiler has finished executing the code inside the function, so we come back out to line 9.
On line 9, we have a RHS reference for the variable bar
.
Now, bar
was declared in the local scope of baz
, but there is a RHS reference for bar
in the global scope.
Since there is no LHS reference for bar
in the global scope, the compiler can’t find a value for bar
and throws a ReferenceError.
But, you might ask, if the function can look outside itself for variables, or a local scope can peek into the global scope to find LHS references, why can’t the global scope peek into a local scope? Well that’s how lexical scope works!
...
// global scope
var baz = function() {
...
// baz's scope
}
...
/// global scope
This is the same code from above which illustrates the scope.
This forms a sort of hierarchy that goes up to the global scope:
baz -> global
.
So, if there is a RHS reference for a variable inside baz
’s scope, it can be fulfilled by a LHS reference for that variable in the global scope.
But the opposite is not true.
What if we had another function inside baz
?
...
// global scope
var baz = function() {
...
// baz's scope
var bar = function() {
...
// bar's scope.
}
}
...
/// global scope
In this case, the hierarchy or the scope chain would look like this:
bar -> baz -> global
Any RHS references inside bar
’s local scope can be fulfilled by LHS references in the global scope or baz
’s scope, but a RHS reference in baz
’s scope cannot be fulfilled by a LHS reference in bar
’s scope.
You can only traverse down a scope chain, not up.
There are other two important things you should know about JavaScript scopes.
Scopes are declared by functions, not by blocks.
Functions can be forward-referenced, variables can’t.
Observe (each comment describes scope at the line that it’s written on):
// outer() is in scope here because functions can be forward-referenced
function outer() {
// only inner() is in scope here
// because only functions are forward-referenced
var a = 1;
//now 'a' and inner() are in scope
function inner() {
var b = 2
if (a == 1) {
var c = 3;
}
// 'c' is still in scope because JavaScript doesn't care
// about the end of the 'if' block, only function inner()
}
// now b and c are out of scope
// a and inner() are still in scope
}
// here, only outer() is in scope
For Loop
Syntax
for ([initialization]); [condition]; [final-expression]) {
// statement
}
The javascript for
statement consists of three expressions and a statement:
initialization - Run before the first execution on the loop.
This expression is commonly used to create counters.
Variables created here are scoped to the loop.
Once the loop has finished its execution, they are destroyed.
condition - Expression that is checked prior to the execution of every iteration.
If omitted, this expression evaluates to true.
If it evaluates to true, the loop’s statement is executed.
If it evaluates to false, the loop stops.
final-expression - Expression that is run after every iteration.
Usually used to increment a counter.
But it can be used to decrement a counter too.
statement - Code to be repeated in the loop
any of these three expressions or the statement can be omitted.
For loops are commonly used to count a certain number of iterations to repeat a statement.
Use a break
statement to exit the loop before the condition expression evaluates to false.
Common Pitfalls
Exceeding the bounds of an array
When indexing over an array many times, it is easy to exceed the bounds of the array (ex.
try to reference the 4th element of a 3 element array).
// This will cause an error.
// The bounds of the array will be exceeded.
var arr = [ 1, 2, 3 ];
for (var i = 0; i <= arr.length; i++) {
console.log(arr[i]);
}
output:
1
2
3
undefined
There are two ways to fix this code.
Set the condition to either i < arr.length
or i <= arr.length - 1
Examples
Iterate through integers from 0-8
for (var i = 0; i < 9; i++) {
console.log(i);
}
output:
0
1
2
3
4
5
6
7
8
Break out of a loop before condition expression is false
for (var elephant = 1; elephant < 10; elephant+=2) {
if (elephant === 7) {
break;
}
console.info('elephant is ' + elephant);
}
output:
elephant is 1
elephant is 3
elephant is 5
Break Statement
The break statement terminates the current loop, switch
or label
statement and transfers program control to the statement following the terminated statement.
break;
If the break statement is used in a labeled statement, the syntax is as follows:
break labelName;
Examples
The following function has a break statement that terminates the while
loop when i is 3, and then returns the value 3 * x.
function testBreak(x) {
var i = 0;
while (i < 6) {
if (i == 3) {
break;
}
i += 1;
}
return i * x;
}
In the following example, the counter is set up to count from 1 to 99; however, the break statement terminates the loop after 14 counts.
for (var i = 1; i < 100; i++) {
if (i == 15) {
break;
}
}
Do While loop
The do...while
loop is closely related to the while
loop.
In the do while loop, the condition is checked at the end of the loop.
Here is the syntax for do...while
loop:
Syntax:
do {
*Statement(s);*
} while (*condition*);
statement(s): A statement that is executed at least once before the condition or Boolean expression is evaluated and is re-executed each time the condition evaluates to true.
condition: Here, a condition is a Boolean expression.
If the Boolean expression evaluates to true, the statement is executed again.
When the Boolean expression evaluates to false, the loops ends.
Example:
var i = 0;
do {
i = i + 1;
console.log(i);
} while (i < 5);
Output:
1
2
3
4
5
For In Loop
The for...in
statement iterates over the enumerable properties of an object, in arbitrary order.
For each distinct property, statements can be executed.
for (variable in object) {
...
}
Required/OptionalParameterDescriptionRequiredVariable: A different property name is assigned to the variable on each iteration.
OptionalObject: an object whose enumerable properties are iterated.
Examples
// Initialize object.
a = { "a": "Athens", "b": "Belgrade", "c": "Cairo" }
// Iterate over the properties.
var s = ""
for (var key in a) {
s += key + ": " + a[key];
s += "<br />";
}
document.write (s);
// Output:
// a: Athens
// b: Belgrade
// c: Cairo
// Initialize the array.
var arr = new Array("zero", "one", "two");
// Add a few expando properties to the array.
arr["orange"] = "fruit";
arr["carrot"] = "vegetable";
// Iterate over the properties and elements.
var s = "";
for (var key in arr) {
s += key + ": " + arr[key];
s += "<br />";
}
document.write (s);
// Output:
// 0: zero
// 1: one
// 2: two
// orange: fruit
// carrot: vegetable
// Efficient way of getting an object's keys using an expression within the for-in loop's conditions
var myObj = {a: 1, b: 2, c:3}, myKeys = [], i=0;
for (myKeys[i++] in myObj);
document.write(myKeys);
//Output:
// a
// b
// c
For Of Loop
The for...of
statement creates a loop iterating over iterable objects (including Array, Map, Set, Arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
for (variable of object) {
statement
}
Description variable: On each iteration a value of a different property is assigned to the variable.object Object whose enumerable properties are iterated.
Examples
Array
let arr = [ "fred", "tom", "bob" ];
for (let i of arr) {
console.log(i);
}
// Output:
// fred
// tom
// bob
Map
var m = new Map();
m.set(1, "black");
m.set(2, "red");
for (var n of m) {
console.log(n);
}
// Output:
// 1,black
// 2,red
Set
var s = new Set();
s.add(1);
s.add("red");
for (var n of s) {
console.log(n);
}
// Output:
// 1
// red
Arguments object
// your browser must support for..of loop
// and let-scoped variables in for loops
function displayArgumentsObject() {
for (let n of arguments) {
console.log(n);
}
}
displayArgumentsObject(1, 'red');
// Output:
// 1
// red
While Loop
The while loop starts by evaluating the condition.
If the condition is true, the statement(s) is/are executed.
If the condition is false, the statement(s) is/are not executed.
After that, while loop ends.
Here is the syntax for the while loop:
Syntax:
while (condition)
{
statement(s);
}
statement(s): A statement that is executed as long as the condition evaluates to true.
condition: Here, the condition is a Boolean expression which is evaluated before each pass through the loop.
If this condition evaluates to true, statement(s) is/are executed.
When the condition evaluates to false, execution continues with the statement after the while loop.
Example:
var i = 1;
while (i < 10)
{
console.log(i);
i++; // i=i+1 same thing
}
Output:
1
2
3
4
5
6
7
8
9